Matching Patterns not Preceded by Certain Characters with Regular Expressions
In Java, regular expressions offer powerful pattern matching capabilities. One specific task is to match a pattern only when it is not preceded by specified characters.
To achieve this, negative lookbehinds can be employed. Negative lookbehinds use the syntax (?
Example:
Consider the string:
String s = "foobar barbar beachbar crowbar bar ";
To match "bar" only when it is not preceded by "foo," use the following regular expression:
\w*(?<!foo)bar
Here's how it works:
Output:
barbar beachbar crowbar bar
Additional Note:
To capture characters before "bar" (e.g., "beach"), add \w* before capturing "bar":
\w*(?<!foo)\w*bar
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3