Garrett Garrett - 1 year ago 77
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:


But that doesn't work.
Any suggestions?

Answer Source

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



(?:          # 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