"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Use Java Regular Expressions to Match Patterns Not Preceded by Specific Characters?

How Can I Use Java Regular Expressions to Match Patterns Not Preceded by Specific Characters?

Posted on 2025-02-06
Browse:423

How Can I Use Java Regular Expressions to Match Patterns Not Preceded by Specific Characters?

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:

  • \w*: Captures any number of word characters (alphabets, numbers, or underscores) before "bar."
  • (? Negative lookbehind that ensures the characters "foo" are not present immediately before "bar."

Output:

barbar
beachbar
crowbar
bar

Additional Note:

To capture characters before "bar" (e.g., "beach"), add \w* before capturing "bar":

\w*(?<!foo)\w*bar
Latest tutorial More>

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