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
Release: 2024-12-08 21:24:22
Original
538 people have browsed it

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 ";
Copy after login

To match "bar" only when it is not preceded by "foo," use the following regular expression:

\w*(?<!foo)bar
Copy after login

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
Copy after login

Additional Note:

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

\w*(?<!foo)\w*bar
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template