Garrett Garrett - 7 months ago 22
Javascript Question

Javascript Regular Expression to match string unless preceeded by backslash

How do I match U1234, but not \U1234 in Javascript?

I can't figure out how to not match the single backslash.
The closest I can get is:

\[\\]{0}U[0-9]{4}\b


But that doesn't work.
Any suggestions?

Answer

JavaScript definitely does not support lookbehind assertions. The next best way to get what you want, in my opinion, would be

(?:^|[^\\])(U[0-9]{4})

Explanation:

(?:          # non-capturing group - if it matches, we don't want to keep it
   ^         # either match the beginning of the string
   |         # or
   [^\\]     # match any character except for a backslash
)            # end of non-capturing group
(U\d{4})     # capturing group number 1: Match U+4 digits
Comments