Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching something if it is not preceded by something else

Tags:

java

regex

With regex in Java, I want to write a regex that will match if and only if the pattern is not preceded by certain characters. For example:

String s = "foobar barbar beachbar crowbar bar "; 

I want to match if bar is not preceded by foo. So output would be:

barbar beachbar crowbar bar 
like image 954
b3bop Avatar asked Feb 16 '12 05:02

b3bop


People also ask

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do you match a character except one regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.

What does \b do in regular expression?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.


2 Answers

You want to use negative lookbehind like this:

\w*(?<!foo)bar 

Where (?<!x) means "only if it doesn't have "x" before this point".

See Regular Expressions - Lookaround for more information.

Edit: added the \w* to capture the characters before (e.g. "beach").

like image 164
Adam Rofer Avatar answered Sep 21 '22 22:09

Adam Rofer


Another option is to first match optional word characters followed by bar, and when that has matched check what is directly to the left is not foobar.

The lookbehind assertion will run after matching bar first.

\w*bar(?<!foobar) 
  • \w* Match 0+ word characters
  • bar Match literally
  • (?<!foobar) Negative lookbehind, assert from the current position foobar is not directly to the left.

Regex demo

like image 33
The fourth bird Avatar answered Sep 21 '22 22:09

The fourth bird