Ben Hernandez
Ben Hernandez

Reputation: 857

Javascript regex without lookbehind

I am using javascript and trying to match mathematical functions such as f(2) or g(1200) but not match things like sqrt(2)

Right now I have

/[a-z]\([\d]+\)/

and that highlights these on regexr

everything is perfect except I don't want that part of sqrt to be selected. I want to lookbehind for letters but javascript doesn't support that, any idea on how I can work around this? Thanks :)

Upvotes: 0

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

Just use a word boundary:

\b[a-z]\(\d+\)

See the regex demo

Since JS regex engine does not support a lookbehind, a logical way out is to utilize a word boundary assertion here: if the letter matched with [a-z] is not preceded with a word character (one from the [a-zA-Z0-9_] range), it is OK to match it - that is when \b comes in very handy.

Alsom, you do not have to place the only shorthand character class pattern into a character class, [\d] will match the same characters as \d.

Upvotes: 3

Related Questions