簡體   English   中英

使用正則表達式替換字符

[英]character getting replaced by using regular expression

String tempprop="(kfsdk)#";
tempprop = tempprop.replaceAll("[^\\s]\\)\\#", "\"?if_exists}");
System.out.println("1"+tempprop+"2");

我希望輸出為

1(kfsdk“?if_exists} 2

但是這個正則表達式的輸出是

1(kfsd“?if_exists} 2

最后k個被修整了,我不知道為什么。

如果tempprop為()#,則輸出應僅為1()#2,且不帶“?if_exists "?if_exists如果沒有空格,則此正則表達式添加"?if_exists ,否則它將按原樣返回字符串

您可以使用負向后看而不是[^\\\\s]因為這會在最終輸出中產生一些影響。 也就是說,環顧四周的寬度為零。

String tempprop="(kfsdk)#";
tempprop = tempprop.replaceAll("(?<!\\s)\\)#", "\"?if_exists}");
System.out.println("1"+tempprop+"2");

輸出:

1(kfsdk"?if_exists}2

說明:

  • (?<!\\s)負向后看,斷言前面沒有空格字符。
  • \\)#匹配文字)#符號。

要從捕獲中排除[^\\s] ,請使用正則表達式(?<![^\\s])\\)\\# 另一種選擇是使用(?<=\\w)\\)\\#強制使用字母,甚至使用強制使用左括號

out = str.replaceAll("(\\(\\w+)\\)\\#", "$1\"?if_exists}");

請參閱此處以獲取更多有關環視(后視和前瞻)的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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