Jackie
Jackie

Reputation: 127

regex match number

I need a regex (JavaScript) to match 2, 23 and not include 37 in the following case.

[B.TARGET.avg(37)]*2 + length(23)

Upvotes: 0

Views: 74

Answers (1)

bobble bubble
bobble bubble

Reputation: 18490

To match outside brackets if between, you need to look ahead, if there's not a closing ]

var re = /\d+(?:\.\d+)?(?![^[]*?\])/g; 
  • \d+(?:\.\d+)? matches one or more digits (optional point number)
  • (?![^[]*?\]) looks ahead, if there is not non-opening brackets, followed by a closing ]

See demo at regex101


The positive lookahead option would be to check if there is only balanced brackets ahead:

var re = /\d+(?:\.\d+)?(?=(?:[^[\]]*\[[^[\]]*\])*[^[\]]*$)/g; 

(?=(?:[^[\]]*\[[^[\]]*\])*[^[\]]*$) looks ahead for an even amount of brackets.

See demo at regex101

Upvotes: 1

Related Questions