Home >Java >javaTutorial >How Can I Use Regex in Java to Match Patterns Only When Not Preceded by Specific Characters?

How Can I Use Regex in Java to Match Patterns Only When Not Preceded by Specific Characters?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 22:46:11746browse

How Can I Use Regex in Java to Match Patterns Only When Not Preceded by Specific Characters?

Matching Patterns not Preceded by Specific Characters using Regex

In Java, regular expressions provide a powerful way to match patterns in strings. Sometimes, you may need to match a pattern only if it is not preceded by certain characters. By leveraging negative lookbehind, regex allows you to achieve this.

Problem:

Consider the following string:

String s = "foobar barbar beachbar crowbar bar ";

We wish to match all occurrences of "bar" that are not immediately preceded by "foo." The desired output would be:

barbar
beachbar
crowbar
bar

Solution:

To accomplish this task, we can use the following regex pattern:

\w*(?<!foo)bar

Breaking down the pattern:

  • w* matches any number of word characters (letters, numbers, or underscores) before the potential match. This portion captures characters like "beach" in "beachbar."
  • (?

By using this pattern, we can successfully match "bar" occurrences that are not preceded by "foo." The result will mirror the desired output.

Additional Notes:

  • For more information on regex negative lookbehind, refer to "Regular Expressions - Lookaround."
  • The w* portion was added later to capture the characters before the pattern (e.g., "beach" in "beachbar").

The above is the detailed content of How Can I Use Regex in Java to Match Patterns Only When 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