zvikachu
zvikachu

Reputation: 279

Java regex challenge - adding a prefix only when needed

I am trying to create a a regex which will add a prefix (foo) to a word (bar) only when it's not there already and when there are multiple appearances of the word bar. Also ignore capitalize letters

String s = " uncle bar, is a foo bar kind of guy when he is at the bar "

so trying the following:

String s = " uncle bar, is a foo bar kind of guy when he is at the bar ";    
Pattern p;
Matcher m; 
p = Pattern.compile("(?i) bar ");
m = p.matcher(s);
if(m.find()){
       s =  s.replaceAll("(?i) bar ", " foo bar ");
}

This will result in adding foo, even when it already there. i.e. "foo foo bar kind of guy" I need a regex to take into consideration the prefix of my pattern when trying to match it.

Thanks in advance

Upvotes: 0

Views: 64

Answers (2)

afzalex
afzalex

Reputation: 8652

You can use negative lookbehind to do this

s.replaceAll("(?i)(?<!foo )bar", "foo bar")

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Use a negative lookbehind assertion.

s.replaceAll("(?i)(?<!\\bfoo )bar\\b", "foo bar");

DEMO

Upvotes: 1

Related Questions