簡體   English   中英

字符串replaceAll中的Java正則表達式:否定的前瞻無法按預期工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM