我在替换用户输入字符串中的特定字符串时遇到问题,但没有生成预期的输出。
String inputString="hellol lol";
String result = inputString.replaceAll("lol", "laugh out loud");
System.out.println("Normal Form:" + result);
输入: 你好哈哈
代码输出: 大声笑出声
预期输出: 你好笑出声
我该如何解决这个问题?谢谢。
最佳答案
replaceAll()
方法使用正则表达式来查找匹配项并替换它们。适当的正则表达式将完成您的工作。使用 \\bol\\b
作为正则表达式。
inputString.replaceAll("\\blol\\b", "laugh out loud");
这里 \\b
是有助于识别 lol
标记的单词边界
关于java - java中替换特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50196946/