首页 文章

Java正则表达式挑战 - 仅在需要时添加前缀

提问于
浏览
0

我正在尝试创建一个正则表达式,它只会在一个单词(bar)中添加前缀(foo),只有当它不存在时以及单词bar的多个外观时才会添加 . 也忽略大写字母

String s =“叔叔吧,当他在酒吧时,他是一个骗子吧”

所以尝试以下方法:

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 ");
}

这将导致添加foo,即使它已经存在 . 即“foo foo bar kind of guy”我需要一个正则表达式,以便在尝试匹配时考虑我的模式的前缀 .

提前致谢

2 回答

  • 1

    您可以使用负向lookbehind来执行此操作

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

    使用负面的lookbehind断言 .

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

    DEMO

相关问题