Nick W
Nick W

Reputation: 907

Regular Expression to stop at specific character

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:

Upvotes: 2

Views: 6857

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

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' ]

Upvotes: 3

John Bollinger
John Bollinger

Reputation: 180181

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.

Upvotes: 0

anubhava
anubhava

Reputation: 785098

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 (.

Upvotes: 2

Related Questions