[英]Java error while using replaceAll("+-", "-")
I'm trying to use String.replaceAll
but I'm getting an error:我正在尝试使用
String.replaceAll
但出现错误:
Here is my code:这是我的代码:
public static String signSimplify (String str) {
String strr = str.replaceAll("--", "+");
String strr2 = strr.replaceAll("-+", "-");
String strr3 = strr2.replaceAll("+-", "-");
return strr3;
}
And, when executed, I get the following error:而且,当执行时,我收到以下错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+-
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at fr.genius.main.Main.signSimplify(Main.java:108)
at fr.genius.main.Main.calcTrinome(Main.java:88)
at fr.genius.main.Main.main(Main.java:69)`
I don't understand why I can't use a replaceAll("+-", "-") but I can when + and - are inversed.我不明白为什么我不能使用 replaceAll("+-", "-") 但是当 + 和 - 颠倒时我可以。
如果您不想要或不需要正则表达式,只需使用replace()
而不是replaceAll()
,它就会像您预期的那样工作。
replaceAll in Java treats the text to replace as a Regular Expression. Java 中的 replaceAll 将要替换的文本视为正则表达式。 You'll need to escape the +.
你需要逃避+。
str.replaceAll("\\+-", "-")
Use the replacement in below technique:使用以下技术中的替换:
String url="abc+-abc";
System.out.println(url.replaceAll("\\+-", "-"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.