I'm using the following javascript to return an array containing the first 2 numerical values found in string
text.match(/(\d+)/g);
How can I stop the search if an open bracket is found and instead return either NaN or zero? For example:
- 10-20 bags (+£1.50) would return 10 and 20
- 20+ bags (+£1.00) would return 20
I'm using the following javascript to return an array containing the first 2 numerical values found in string
text.match(/(\d+)/g);
How can I stop the search if an open bracket is found and instead return either NaN or zero? For example:
- 10-20 bags (+£1.50) would return 10 and 20
- 20+ bags (+£1.00) would return 20
-
If you're trying to match
X-Y
, then match that, rather than matching both numbers separately. What exactly are you trying to match? There is probably a better solution. – Kendall Frey Commented Aug 28, 2014 at 14:08
3 Answers
Reset to default 3Use a lookahead in your regex in order to match all the numbers before the first (
,
\d+(?=[^()]*\()
Example:
> "10-20 bags (+£1.50)".match(/\d+(?=[^()]*\()/g);
[ '10', '20' ]
> "20+ bags (+£1.00)".match(/\d+(?=[^()]*\()/g);
[ '20' ]
You can use this regex using lookahead:
/(\d+)(?=.*\()/
RegEx Demo
Here (?=.*\()
is called lookahead that makes sure match \d+
if it is not followed by an opening (
.
If you really need the full generality you requested -- that is, if the lines being matched don't necessarily contain exactly one (
-- then I think the only solution is to first match the lead text before any parenthesis (i.e. /^([^(]*)/
) and then select your digit strings from that.
Javascript regexes do not support lookbehind, which is what you need to do the job in the full generality you specified with a single regex.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744372117a4571007.html
评论列表(0条)