【问题标题】:Java regex in String replaceAll: negative look ahead does not work as expectedString replaceAll 中的 Java 正则表达式:否定前瞻无法按预期工作
【发布时间】:2023-03-18 06:57:01
【问题描述】:

我正在尝试处理文本并替换所有以“www”开头的出现。用某个词(在这种情况下是“香蕉”),但我想排除所有在“www”之前有“http://”的情况。

当我使用积极的前瞻时,它会起作用(只有 http://www 的情况会改变),但是当我使用消极的前瞻时 - 两个词都会改变。

你能帮我解决这个问题吗?

String baseString = "replace this: www.q.com and not this:http://www.q.com";
String positiveLookahead = baseString.replaceAll("(?:http://)www([^ \n\t]*)", "Banana");
String negativeLookahead = baseString.replaceAll("(?!http://)www([^ \n\t]*)", "Banana");

//positiveLookahead works (changes only the scond phrase), but positiveLookahead does not (changes both)

【问题讨论】:

  • 你不应该在后面看,而不是在前面吗?
  • @khelwood 你是对的,请参阅 Wiktor 的回复。谢谢!

标签: java regex string string-matching


【解决方案1】:

使用否定的lookbehind(?<!http://)

String negativeLookahead = baseString.replaceAll("(?<!http://)www[^ \n\t]*", "Banana");

(?&lt;!http://)www[^ \n\t]* 模式匹配:

  • (?&lt;!http://) - 字符串中没有紧跟在http:// 前面的位置
  • www - 文字 www 子字符串
  • [^ \n\t]* - 除空格、换行符和回车符之外的任何 0+ 字符(您可能想改用 \\S*)。

【讨论】:

  • 谢谢,可以了 :) 那么前瞻有什么作用呢?
  • @TalSheffer 否定前瞻匹配字符串中未立即跟随的位置与模式,因此(?!a)b 始终等于bb不是a
  • 知道了。那么负前瞻的合法用途是什么?
  • @TalSheffer 很多。例如,请参阅this today's answer of mine。有关negative lookahead herehere 的更多信息。
  • 非常感谢!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 2017-10-08
相关资源
最近更新 更多