0

考虑以下字符串:

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

我有一个ArrayList<ArrayList<String>> anaphora正确的匹配和句子编号以及ArrayList<String> sentences来自s. 两者看起来像这样:

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.

预期的输出将是这样一种方式,即 'he' 被 'Ralph' 取代:

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

问题如何修复我的正则表达式替换,以便只替换正确的“他”?

4

2 回答 2

1

如上所述,您可以使用单词边界,例如:

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"));

印刷:

拉尔夫走在街上,拉尔夫看到玛丽并爱上了她。

于 2013-04-17T10:17:28.263 回答
0

你需要小心空白。所以你的正则表达式应该只做替换,如果被替换的字符串是一个单词。

于 2013-04-17T10:18:19.870 回答