4
$\begingroup$

examples

text1 = " climb   -  95/ 85     0.18   low     -  4680"

text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"#

How can I get with regex in Mathematica as results:

split_text1 = {'95', '85', '0.18', '4680'}

split_text2 = {'3', '80.0','0.0', '0.0', 0.0}
$\endgroup$
2
  • $\begingroup$ Select[NumericQ] /@ ImportString[text1, "Table"]? Although this will fail to return $95$ because it is not separated by a space ... $\endgroup$
    – Domen
    Feb 14, 2022 at 13:00
  • $\begingroup$ TextCases[text1, "Number"] works for the first one but not the second. Are you committed to regex specifically or are other pattern matching solutions acceptable as well? In either case, is seems that StringCases would be the answer. $\endgroup$
    – MarcoB
    Feb 14, 2022 at 13:02

2 Answers 2

7
$\begingroup$
text1 = " climb   -  95/ 85     0.18   low     -  4680";
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00  .00000E+00 /";

R = RegularExpression["[+-]?\\d*(\\.\\d|\\d\\.|\\d)\\d*([eE][+-]?\\d+)?"];

getnumbers[s_String] := Interpreter["Number"]@StringCases[s, R]

getnumbers[text1]
(*    {95, 85, 0.18, 4680}    *)

getnumbers[text2]
(*    {3, 80., 0., 0., 0.}    *)

The regular expression is a bit complicated by the (\\.\\d|\\d\\.|\\d) alternatives: either we have a dot followed by a number, or a number followed by a dot, or just a number, but never just a dot alone. This allows matching 1.0, 2. and .3 but not matching ..

$\endgroup$
6
$\begingroup$
StringCases[text1, NumberString]
{"95", "85", "0.18", "4680"}

For text2 we need additional processing:

StringCases[{text1, text2}, 
  {n : NumberString ~~ "E" ~~ _ ~~ NumberString :>
     ToString @ Internal`StringToDouble[n], 
   NumberString}]
{{"95", "85", "0.18", "4680"}, {"3", "80.", "0.", "0.", "0."}}
$\endgroup$
0

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.