[英]Java regex in String replaceAll: negative look ahead does not work as expected
我正在尝试处理文本并替换所有以“ 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)
在(?<!http://)
使用负向后看 :
String negativeLookahead = baseString.replaceAll("(?<!http://)www[^ \n\t]*", "Banana");
(?<!http://)www[^ \\n\\t]*
模式匹配:
(?<!http://)
-字符串中不立即以http://
www
文字www
子字符串 [^ \\n\\t]*
-除空格,换行符和回车符以外的任何0+字符(可能您想尝试使用\\\\S*
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.