Nicolas
Nicolas

Reputation: 155

JavaScript regex to match a character only if preceded with another character

I have the following regular expression:

[^0-9+-]|(?<=.)[+-]

This regex matches either a non-digit and not + and - or +/- preceded by something. However, positive lookbehind isn't supported in JavaScript regex. How can I make it work?

Upvotes: 5

Views: 5720

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The (?<=.) lookbehind just makes sure the subsequent pattern is not located at the start of the string. In JS, it is easy to do with (?!^) lookahead:

[^0-9+-]|(?!^)[+-]
         ^^^^^ 

See the regex demo (cf. the original regex demo).

Upvotes: 4

Related Questions