4
$\begingroup$

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.

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

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.

$\endgroup$
  • 2
    $\begingroup$ 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. $\endgroup$ – J. M. is away Apr 13 '16 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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