javascript - Regular Expression to stop at specific character - Stack Overflow

I'm using the following javascript to return an array containing the first 2 numerical values foun

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
Share Improve this question edited Aug 28, 2014 at 14:06 axelduch 10.9k2 gold badges33 silver badges50 bronze badges asked Aug 28, 2014 at 14:03 Nick WNick W 9272 gold badges16 silver badges32 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 3

Use 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信