Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

like image 275
Nicolas Avatar asked Oct 17 '22 13:10

Nicolas


1 Answers

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

like image 101
Wiktor Stribiżew Avatar answered Oct 21 '22 07:10

Wiktor Stribiżew