Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You want to use negative lookbehind like this:

 \w*(?<!foo)bar

Where (?<!x) means "only if there is no "x" before this point".

See Regular Expressions - Lookaround for more information.

Edit : Added \w* to capture the above characters (eg "beach").

over 4 years ago · Santiago Trujillo Report

0

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

The lookbehind assertion will be executed after matching the bar first.

 \w*(?<!foo)bar
  • \w* Matches 0+ word characters

  • bar Match literally

  • (?<!foobar) Negative look back, assert from current position foobar is not directly to the left.

Regular expression demo

over 4 years ago · Santiago Trujillo Report

0

In some cases, it could be easier to optionally include the preceding part, then skip those matches in a second step. For instance, to find numbers that don't start with a "+":

if (preg_match_all('/(\+?[0-9][0-9\s\-].*[0-9])/s',$text,$matches)) {
    foreach($matches[1] as $match) {
        if(substr($match,0,1) == '+'){
            continue;
        }
        // continue processing
    }
}

The negative look behind did not work since it would still match 2+ digits, but it would not include the first digit in the match. For instance +1234 would be returned as 234.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!