3 回答
TA贡献1853条经验 获得超6个赞
要替换所有出现的子字符串,您不需要模式。您可以使用String.replace():
String input = "÷x%abc÷x%def÷x%";
String output = input.replace("÷x%", "÷1x#1$%");
System.out.println(output); // ÷1x#1$%abc÷1x#1$%def÷1x#1$%
根据方法javadoc:
用指定的文字替换序列替换此字符串中与文字目标序列匹配的每个子字符串。
TA贡献1712条经验 获得超3个赞
在 Java 正则表达式中,您必须转义 $ 符号。
如果您写 $%,您将指代不存在的组 %。
你可以试试:
try {
String string = "÷x%2%x#3$$@";
String myregex = "÷x%";
String replace = "÷1x#1\\$%";
String resultString = string.replaceAll(myregex, replace);
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}
添加回答
举报