String replaceAll 中的 Java 正则表达式:负面展望未按预期工作 [英] Java regex in String replaceAll: negative look ahead does not work as expected
本文介绍了String replaceAll 中的 Java 正则表达式:负面展望未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试处理文本并替换所有以www"开头的出现.用某个词(在这种情况下为香蕉"),但我想排除在www"之前有http://"的所有情况.
I am trying to process text and replace all the occurence that start with "www." with a certain word (in this cases "Banana"), but I want to exclude all the cases in which there is "http://" before the "www".
当我使用正向前瞻时它可以工作(只有 http://www 案例更改),但是当我使用负面展望 - 两个词都发生了变化.
When I use a positive lookahead it works (only the http://www case changes), but when I use a negative lookahead - both words change.
你能帮我解决这个问题吗?
Can you help me with this one?
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)
推荐答案
使用否定的 回顾, (?:
String negativeLookahead = baseString.replaceAll("(?<!http://)www[^ \n\t]*", "Banana");
(?<!http://)www[^ \n\t]*
模式匹配:
(?<!http://)
- 字符串中没有紧跟在http://
前面的位置www
- 文字www
子字符串[^ \n\t]*
- 除了空格、换行符和回车之外的任何 0+ 个字符(可能你想试试\\S*
代替).
(?<!http://)
- a location in the string that is not immediately preceded withhttp://
www
- a literalwww
substring[^ \n\t]*
- any 0+ chars other than space, newline and carriage return (probably you want to try\\S*
instead).
这篇关于String replaceAll 中的 Java 正则表达式:负面展望未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文