# Extracting integers from a string

Imagine I have a block of text that contains words and numbers. I want to extract all the integers from the text. Thus, if the input is

"Now is the time for all good men to come 2 the aid of their country"


the correct output should be 2 (or {2}).

Given the input

"1 is looking for 25 people to eat 3.14159"


the correct output should be {1, 25}.

I have been working through a complex process with Characters[] and Select[], but I think a much simpler solution must be possible.

• Cases[ToExpression /@ StringCases[string, NumberString], _Integer] Apr 13 '16 at 16:43
• "Here's 1. Is it 1 or 1. ?"
– Kuba
Apr 13 '16 at 16:47
• @Kuba That would be an integer. march's solution is good but misses that one. Apr 13 '16 at 16:50
• Define integer then, MatchQ[1., _Integer] is not enough.
– Kuba
Apr 13 '16 at 16:51
• "Is 3/2 less than 2 or 3? How about -1, what can be done?" Apr 13 '16 at 19:37

You can get this result by mixing StringExpression with RegularExpression.

Regular expressions have the ability to perform a negative look-ahead. This can be used to insure that no numbers which have a decimal followed numbers are matched.

getIntegers[s_String] :=
StringCases[ s,
(StartOfString | Whitespace) ~~ u : Repeated["-", {0, 1}] ~~
n : DigitCharacter .. ~~ RegularExpression["(?![\\./]\\d)"] :>
(If[u == "-", -1, 1] FromDigits@n)]


Then

getIntegers["1 is looking for 25 people to eat 3.14159"]
(* {1, 25} *)

getIntegers["Here's 1. Is it 1 or 1. ?"]
(* {1, 1, 1} *)

getIntegers["Is 3/2 less than 2 or 3? How about -1, what can be done?"]
(* {2, 3, -1} *)


Hope this helps.

• I approve, but the purpose of my comment above was to force OP to consider other possibilities; your result may or may not be what he actually wants. Apr 13 '16 at 21:21