在 Java 中用微小的修改替换字符串模式



我有一个正则表达式模式,可以匹配"工作日"、"某件事"等文本。我想用"工作日"、"某件事"替换这种模式。

我做了如下事情:

Pattern alpha_only = Pattern.compile("[a-zA-Z]+\-[a-zA-Z]+");
Matcher alonly_matcher = alpha_only.matcher(token);
while (alonly_matcher.find()){
    old_val = alonly_matcher.group(0);
    new_val = old_val.replaceAll("\-", " ");
    token = token.replace(old_val, new_val);
}

但这在字符串包含许多连字符的情况下不起作用。例如,在类似

"This is some-example text with - multiple hyphens and 45-55 week-day"

它不应删除 45-55 等之间的连字符。我该如何解决这个问题?我是正则表达式的新手。

您已经拥有了所需的所有信息。 只需使用捕获组。

Pattern alphaHyphenated = Pattern.compile("([a-zA-Z]+)\-([a-zA-Z]+)");
Matcher alphaMatcher = alphaHyphenated.matcher(token);
return alphaMatcher.replaceAll("$1 $2");

或者,简单地

return token.replaceAll("([a-zA-Z]+)\-([a-zA-Z]+)", "$1 $2");

当然,每次运行时都会编译模式。 上面的alphaHyphenated可以是编译时常量。

最新更新