Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a text file containing many, many lines of text like test in the following:

test = "word  123  456    7890.000      0.12000";

I would like to extract all of the "string representations of integers." However, I need to be clear about what I would like. In test above, I would like the output to be:

{"123", "456"}

since I am only interested in actual, isolated (delimited by spaces) string representations of integers. Yes, 7890 is an integer, but in test above, it is not isolated, so I do not want my function to return it (since 7890.000 is a decimal).

In the case of test, I could use this:

StringCases[test, Repeated[DigitCharacter, 3]][[1 ;; 2]]

which returns

{"123", "456"}

However, this is not general, because my string may contain more than two string representations of integers. So I would like my function to also take this input:

test = "word  123  456  123    7890.000      0.12000";

and return:

{"123", "456", "123"}

I have thought about using StringSplit followed by ToExpression and IntegerQ, but this seems like it would be very (unnecessarily?) complicated. Perhaps Mathematica has something better built in that I can use?

Do you have any advice? Thanks!

share|improve this question

3 Answers 3

up vote 6 down vote accepted

I quite like Mathematica's StringExpression. A bit longer than regular expressions but easier to read.

StringCases[test, " " ~~ d : DigitCharacter.. ~~ " " -> d]

{"123", "456", "123"}

(Of course this does require two spaces between integers).

share|improve this answer
1  
You don't actually need two spaces since you can set the option Overlaps->True. –  dws Aug 1 '12 at 18:56

Regular Expressions are your friend:

StringTrim[StringCases["word  123  456  123    7890.000      0.12000", RegularExpression[" \\d+ "]]]

This returns

{"123", "456", "123"}
share|improve this answer

You can do it with Select and StringCases with NumberString as:

Select[StringCases[test, NumberString], IntegerQ@ToExpression@# &]
(* {"123", "456", "123"} *)

Add a Rationalize to the test if you also need integer numbers with the head Real.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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