Java replaceAll:无法用反斜杠替换字符串

时间:2018-07-24 22:31:05

标签: java regex string replace substring

在我的Java程序中,我试图替换在字符串(从paloalto\sanjose\)中包含反斜杠的子字符串。但是,即使我使用双反斜杠来减轻反斜杠作为转义字符的影响,我仍然会收到以下错误:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 9
paloalto\
         ^
    at java.util.regex.Pattern.error(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 Main.main(Main.java:8)

下面是我的代码:

String original = "paloalto\\adam paloalto\\jack paloalto\\justin";
System.out.println("original = " + original);

String sanjose = original.replaceAll("paloalto\\", "sanjose\\");
System.out.println("backgammon  = " + sanjose);

3 个答案:

答案 0 :(得分:4)

replace将为您工作,replaceAll使用正则表达式,而\\是特殊字符的前缀,例如\\s是空格,\\.是任何字符等

String test = "paloalto\\paloalto\\";
test = test.replace("paloalto\\", "sanhose\\");
System.out.println(test);

对于replaceAll,您可以将Pattern.quote的结果用作第一个参数,并将Matcher.quoteReplacement的结果用作第二个参数:

test = test.replaceAll(Pattern.quote("paloalto\\"), Matcher.quoteReplacement("sanjose\\"));

Documentation.

答案 1 :(得分:3)

您需要四个反斜杠:用于在Java中声明String的两个反斜杠(在实际字符串中将是一个反斜杠),并且在正则表达式中需要两个反斜杠,因为反斜杠再次是regex引擎的特殊字符:

original.replaceAll("paloalto\\\\", "sanjose\\\\");

如果您更容易阅读,可以使用Pattern.quote()

original.replaceAll(Pattern.quote("paloalto\\"), Matcher.quoteReplacement("sanjose\\"));

答案 2 :(得分:0)

您需要为正则表达式提供replaceAll函数,并且\(backspace)是Java中的转义字符。这就是为什么您需要重复4次以捕获字符串。

    String original = "paloalto\\adam paloalto\\jack paloalto\\justin";
    System.out.println("original = " + original);

    String sanjose = original.replaceAll("paloalto\\\\", "sanjose\\\\");
    System.out.println("backgammon  = " + sanjose);

此片段将完成您想要的操作。其输出是

original = paloalto\adam paloalto\jack paloalto\justin
backgammon  = sanjose\adam sanjose\jack sanjose\justin