用另一个单词替换所有出现的单词
我正在写一个正则表达式来匹配每次出现的“japan”并用“japan”替换它。。为什么下面的代码不起作用?“日本”可以在一句话中多次出现,也可以在一句话的任何地方出现。我要替换所有事件
public static void testRegex()
{
String input = "The nonprofit civic organization shall comply with all other requirements of section 561.422, japan laws, in obtaining the temporary permits authorized by this act.";
String regex = "japan";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
System.out.println(input.matches(regex));
System.out.println(input.replaceAll(regex, "Japan"));
}
# 1 楼答案
replaceAll
正在按预期工作根据您的评论:
此语句的计算结果为
false
as}不是正则表达式,您可以这样做
String#matches
与完整的String
匹配。由于String
{# 2 楼答案
input.matches(regex)
用^
和$
自动锚定模式。只需用.*
包围您的模式即可进行匹配但是那样的话,
replaceAll
就不起作用了。因此,您必须将(.*?)japan(.*?)
替换为$1Japan$2
# 3 楼答案
这里不需要正则表达式,也不需要模式和匹配器类。简单地使用
String.replace()
就可以了: