匹配字符串÷x%的正则表达式

我一直在尝试创建一个匹配以下模式的正则表达式:


÷x%


这是我的代码:


String string = "÷x%2%x#3$$@";

String myregex = "all the things I've tried";

string = string.replaceAll(myregex,"÷1x#1$%");

我尝试了以下正则表达式:(÷x%) , [÷][x][%] , [÷]{1}[x]{1}[%]{1}


我正在使用 NetBeans IDE,它给了我一个


非法组引用


但是,当我将 string 的值更改为其他内容时,例如一个单词。


NetBeans 没有例外。


任何想法,谢谢


料青山看我应如是
浏览 158回答 3
3回答

墨色风雨

要替换所有出现的子字符串,您不需要模式。您可以使用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:用指定的文字替换序列替换此字符串中与文字目标序列匹配的每个子字符串。

交互式爱情

在 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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java