How do I match “not” with more characters in the Java regular expression pattern?
•
Java
In Java regular expressions, use [^ x] to match "not" with a char
I wonder how to match more characters?
I use [^ 789], which is wrong
String text="aa(123)bb(456)cc(789)dd(78)"; text=text.replaceAll("\\([^789].*?\\)",""); System.out.println(text);
The result I want is:
aabbcc(789)dd
How do I fix my regular expressions?
Thank you very much:)
Solution
You can use negative lookahead:
"\\((?!789\\)).*?\\)"
explain:
\\( Match a literal open parenthesis "(" (?! Start negative lookahead 789\\) Match literal "789)" ) End lookahead .*? Match any characters (non-greedy) \\) Match a literal close parenthesis ")"
If the pattern in the negative look ahead matches, the negative look forward does not match
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码