Home >Java >javaTutorial >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?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 21:24:22511browse

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

The above is the detailed content of How Can I Use Java Regular Expressions to Match Patterns Not Preceded by Specific Characters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn