Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java RegExp group negation possible?

Tags:

java

regex

I have the following regexp: (["'])(\\\1|[^\1])+\1

Obviously it could not be compiled because [^\1] is illeagal.

Is it possible to negate a matched group?

like image 962
Savva Mikhalevski Avatar asked Oct 09 '22 09:10

Savva Mikhalevski


1 Answers

You can't use backreferences in a positive or negative character class.

But you can achieve what you want using negative lookahead assertions:

(["'])(?:\\.|(?!\1).)*\1

Explanation:

(["'])    # Match and remember a quote.
(?:       # Either match...
 \\.      # an escaped character
|         # or
 (?!\1)   # (unless that character is identical to the quote character in \1)
 .        # any character
)*        # any number of times.
\1        # Match the corresponding quote.
like image 129
Tim Pietzcker Avatar answered Oct 12 '22 10:10

Tim Pietzcker