Reputation: 2423
I have some strings that I'd like to extract the numbers from. The string can have a variety of formats such that:
something on the wing$(0.55) $0.75 $(0.10)
I'd like to capture the groups such that the end result is:
I'll never know if there is going to be a '$' or if the number will be a decimal or how many numbers I need to capture (i.e., in this example there are 3 numbers but there could be 4). Right now I have ([\w\s]*)([\W\d]*)
which captures the string and the values:
But cannot seem to parse the individual values.
Upvotes: 1
Views: 50
Reputation: 26161
Even without any captures this will most probably do the job the way you wanted. Since there are no capture parenthesis it will capture as many data figures following the sentence and return in an array.
^[\w\s]+|[\d\.()]+?(?=\s|$)
var r = /^[\w\s]+|[\d\.()]+?(?=\s|$)/g,
s = "something on the wing$(0.55) $0.75 $(0.10) $12.75 €(4.25)",
m = s.match(r);
document.write("<pre>" + JSON.stringify(m, null, 2) + "</pre>");
Upvotes: 1
Reputation: 626845
You may split
with the following regex:
/\s*\$?(\(?\d*\.?\d+\)?)\s*/
The pattern matches
\$?
- an optional $
(since it may be present or absent, but we need to exclude it from the results) (\(?\d*\.\d+\)?)
- Group 1 (captured values are output to the resulting array with split
) matching a float value inside optional parentheses:
\(?
- an optional (
\d*
- zero or more digits\.?
- an optional .
\d+
- 1+ digits\)?
- an optional )
\s*
- will match zero or more whitespaces (so as not to trim the elements of the resulting array)See the JS demo:
var re = /\s*\$?(\(?\d*\.?\d+\)?)\s*/;
var str = 'something on the wing$(0.55) $0.75 $(0.10)';
var res = str.split(re).filter(Boolean); // .filter(Boolean) will remove empty values
document.body.innerHTML = "<pre>" + JSON.stringify(res,0,4) + "</pre>";
Upvotes: 1
Reputation: 174706
I should do splitting.
alert('something on the wing$(0.55) $0.75 $(0.10)'.split(/\s*\$\s*/))
Upvotes: 2