How can I split strings with regex so that only numbers are selected

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}

• Select[NumericQ] /@ ImportString[text1, "Table"]? Although this will fail to return $95$ because it is not separated by a space ... Feb 14, 2022 at 13:00
• 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. Feb 14, 2022 at 13:02

2 Answers

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 ..

StringCases[text1, NumberString]

{"95", "85", "0.18", "4680"}


For text2 we need additional processing:

StringCases[{text1, text2},
{n : NumberString ~~ "E" ~~ _ ~~ NumberString :>
ToString @ InternalStringToDouble[n],
NumberString}]

{{"95", "85", "0.18", "4680"}, {"3", "80.", "0.", "0.", "0."}}
`