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

1 Answer 1

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$
1
  • 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$ Apr 13, 2016 at 21:21

Your Answer

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

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