gpt4 book ai didi

Java:正则表达式替换字符串

转载 作者:行者123 更新时间:2023-12-01 14:40:06 25 4
gpt4 key购买 nike

考虑以下字符串:

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.

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

最佳答案

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

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

打印:

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

关于Java:正则表达式替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com