3
$\begingroup$

I have a text file that has thousands of questions and blanks for the answer, like this:

1) This is the first question 1)______

2) This is the second question 2)______

3)...

What I want to do is to extract the questions, and put them in a spreadsheet (I'm going to end up putting them in a database). I tried reading through Mathematica's Working with Strings page, but I couldn't figure out how to do it! Can someone please let me know how to do this? Thanks!

$\endgroup$

1 Answer 1

7
$\begingroup$

I'll use a slightly modified example:

str = "1) This is the first question 1)______

 2) This is the second question 2)______

 ...

 10) This is the tenth question 10)______"

One can use either StringExpression[] or RegularExpression[] in StringCases[] for this; here's how:

StringTrim /@ StringCases[str,
                          n : DigitCharacter .. ~~ ")" ~~ s__ ~~ n_ ~~ ")" :> s]

or

StringTrim /@ StringCases[str, RegularExpression["(\\d+\\))(.+)\\1"] -> "$2"]

which should both yield {"This is the first question", "This is the second question", "This is the tenth question"}.

$\endgroup$
14
  • 1
    $\begingroup$ I wonder why people insist on hammering a screw and screwing a text processing problem $\endgroup$ Commented Nov 11, 2015 at 6:13
  • 1
    $\begingroup$ Could've been worse; at least it wasn't parsing XML with regex. $\endgroup$ Commented Nov 11, 2015 at 10:05
  • 1
    $\begingroup$ @NicolasJosephScozzaro Of course. I'm really glad you asked. For example, the unix-born text processing programs (now available on almost every platform) perl, awk or sed are much better suited for these tasks than Mathematica. Your problem is a one liner in any of them. In particular you're up and running in awk in -perhaps- one to three hours depending on your background, and it is a very nice language to learn $\endgroup$ Commented Nov 11, 2015 at 15:37
  • 1
    $\begingroup$ @NicolasJosephScozzaro: There are great websites like regex101, where you can test regular expressions online. If you plan to do a lot of text processing, do yourself a favor and google for tutorials about regular expressions. They're not hard to use, and make text processing so much easier... $\endgroup$ Commented Nov 11, 2015 at 17:52
  • 1
    $\begingroup$ @belisariushassettled, the Mathematica code at least in this answer is also a one-liner - can you give examples of one-liners in the Unix tools that take a lot more effort in M? $\endgroup$ Commented Nov 11, 2015 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.