簡體   English   中英

Java:正則表達式替換字符串

[英]Java: regex replace string

考慮以下字符串:

s = "Ralph was walking down the street, he saw Mary and fell in love with her. Judy loves her hair."

我有一個具有正確匹配項和句子編號的ArrayList<ArrayList<String>> anaphora ,以及具有s的句子的ArrayList<String> sentences 兩者都看起來像這樣:

anaphora.get(0) = [0, Ralph, he]
anaphora.get(1) = [0, Mary, her]
anaphora.get(2) = [0, the street]
anaphora.get(3) = [1, Judy, her]
anaphora.get(4) = [1, her hair]

sentences.get(0) = Ralph was walking down the street, he saw Mary and fell in love with her.
sentences.get(1) = Judy loves her hair.

現在,在嘗試替換子字符串時出現了問題。

sentence = sentences.get(0);
if (anaphora.get(0).size()>2){
    example1 = sentence.replaceAll("[^a-zA-Z]"+anaphora.get(0).get(i)+"[^a-zA-Z]", anaphora.get(0).get(1));
    example2 = sentence.replaceAll(anaphora.get(0).get(i), anaphora.get(0).get(1));
}

輸出將是:

example1 = Ralph was walking down the street,Ralphsaw Mary and fell in love with her.
example2 = Ralph was walking down tRalph street, Ralph saw Mary and fell in love with Ralphr.

預期的輸出將以這樣的方式將“他”替換為“拉爾夫”:

Ralph was walking down the street, Ralph saw Mary and fell in love with her.

問題如何修復正則表達式替換,以便僅替換正確的“他”?

如上所述,您可以使用單詞邊界,例如:

String s = "Ralph was walking down the street, he saw Mary and fell in love with her.";
System.out.println(s.replaceAll("\\bhe\\b", "Ralph"));

印刷品:

拉爾夫走在街上,拉爾夫看見瑪麗,愛上了她。

您需要注意空白。 因此,如果被替換的字符串是一個單詞,則您的正則表達式僅應進行替換。

暫無
暫無

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

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