Reputation: 7392
When I try this:
"12.3 xxx4.56 23yyy".match(/\d+/ig)
I get this output:
["12", "3", "4", "56", "23"]
I would like this:
["12.3", "4.56", "23"]
What's the correct regex?
Upvotes: 1
Views: 153
Reputation: 20014
How about this:
"12.3 xxx4.56 23yyy".match(/([\d.]+)/g)
i
seems to be unnecessary since you are only searching for number i
case insensitive is unnecessary.
Upvotes: 1
Reputation: 2476
You can use an optional group in the regex to handle this case. Like so:
"12.3 xxx4.56 23yyy".match(/\d+(\.\d+)?/ig)
=> Array [ "12.3", "4.56", "23" ]
The (...)?
syntax means that everything inside is optional - if present it will be matched, but if not it won't prevent a match. The ?
alone could also be applied to a single term.
Upvotes: 1