Jeff
Jeff

Reputation: 2423

Regex for variable string

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:

  1. something on the wing
  2. (0.55)
  3. 0.75
  4. (0.10)

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:

  1. something on the wing
  2. $(0.55) $0.75 $(0.10)

But cannot seem to parse the individual values.

Upvotes: 1

Views: 50

Answers (3)

Redu
Redu

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|$)

Regular expression visualization

Debuggex Demo

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

Wiktor Stribiżew
Wiktor Stribiżew

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

Avinash Raj
Avinash Raj

Reputation: 174706

I should do splitting.

alert('something on the wing$(0.55) $0.75 $(0.10)'.split(/\s*\$\s*/))

Upvotes: 2

Related Questions