Thousands separator (comma) option for NumberString/StringCases?
I would just go to RegExp:
StringCases[" 1,142.123 ", RegularExpression["\\s[0-9,.]+\\s"], 1]
(* {" 1,142.123 "} *)
You could also go with:
ImportString[" 1,142.123 ","List"]
Though that will automatically change it to Numeric
, which doesn't seem to be what you want...
This is admittedly a bit of a hack, but you could remove the commas first, using StringReplace
:
StringCases[
StringReplace[" 1,142.123 ", "," -> ""],
Whitespace ~~ NumberString ~~ Whitespace, 1]
(* ==> {" 1142.123 "} *)
Regular expressions are nice, but there is no need to use them here.
numString = (NumberString | ",") .. ;
StringCases[" 1,142.123 ", Whitespace ~~ numString ~~ Whitespace, 1]
{" 1,142.123 "}
The form above is admittedly not robust as a valid number string should not start or end with a comma or have two decimal points, and I believe the comma should not immediately precede a decimal point or appear to its right side. The easiest way I can think to preclude these is to check for them explicitly:
numString = x : (NumberString | ",") .. /;
! StringMatchQ[x, ",*" | "*," | "*.*,*" | "*,.*" | "*.*.*"];
StringCases[" 1,2. ,3 4, 5.6,7,.89 0.1.2sam, i am ", numString]
{"1,2.", "3", "4", "5.6", "7", ".89", "0.1", ".2"}