我需要更改单个字符串的几个部分,其中指定的部分有一些共同的字符;例如:
worker => working
work => worked
note :: "=>" means "changes to"
使用如下代码会产生大量错误:
String txt = "work like a real worker";
String txt2 = txt.replace("worker", "working").replace("work", "worked");
As I tested the codes above, they output "worked like a real workeding", however I need to get "worked like a real working".
最佳答案
如果您使用replaceAll
而不是replace
,您可以使用正则表达式。正则表达式将允许您使用 \b
来表示 word boundaries .这样做,您只会替换整个单词,而不是像您现在所做的那样替换单词的一部分。
String txt2 = txt.replaceAll("\\bworker\\b", "working").replaceAll("\\bwork\\b", "worked");
关于java - 当部分具有共同字符时如何替换字符串的多个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57074216/