在Java中使用replace函数

在Java中使用replace函数,java,Java,我正在尝试使用replace函数替换以下字符串中的“,”和“-” String foo = "('UK', 'IT', 'DE')"; 我正在尝试使用以下代码来执行此操作- (foo.contains("('")?foo.replaceAll("('", ""):foo.replace("'",""))?foo.replaceAll("')",""):foo 但它的失败是- java.util.regex.PatternSyntaxException:索引2附近的未关闭组 我在这里遗漏了什么

我正在尝试使用replace函数替换以下字符串中的“,”和“-”

String foo = "('UK', 'IT', 'DE')";
我正在尝试使用以下代码来执行此操作-

(foo.contains("('")?foo.replaceAll("('", ""):foo.replace("'",""))?foo.replaceAll("')",""):foo
但它的失败是-

java.util.regex.PatternSyntaxException:索引2附近的未关闭组

我在这里遗漏了什么吗?

replaceAll将a作为其搜索模式。由于是正则表达式中的特殊字符,因此需要对其进行转义:“\\”。此外,不需要contains测试:

最后,您可以将所有替换项组合成一个正则表达式:

final String bar = foo.replaceAll("\\(?'([^']*)'\\)?", "$1");
// Output: UK, IT, DE

这将用不带引号的内容替换字符串中每个引用的单引号部分,并允许和放弃周围的开始括号和结束括号。

foo.replaceAll['],将使工作像其他答案和错误消息指出的那样进行。

,replaceAll处理正则表达式,其中,左括号具有特殊含义。出于同样的原因,即使在替换参数中,某些字符也有特殊的含义

如果您想绝对确保字符串的行为与字符串一样,有两种内置的quote方法,它们都是静态的,用于中和模式:

用于包装替换模式 用于包装替换件 尝试将所有两个符号替换为$SYMBOL的示例代码:

输出:


当然,当人们了解这些方法时,他们早已习惯于手动转义特殊字符。

那'?@user85421是的,我想。但我必须解释为什么OP的代码不起作用,然后用它作为最终完整解决方案的垫脚石。OP不是要使用正则表达式,只是简单的替换。在这里使用正则表达式真是太过分了。@Olivier当然,他们本不打算使用正则表达式,但他们意外地使用了正则表达式,而且正则表达式对于Java中的一般字符串处理来说是不可避免的。例如,使用replace不能只替换一个实例,因此了解如何使用正则表达式很重要。我也不同意在这里使用正则表达式是过分的。如果没有正则表达式,则必须使用不同的子字符串重复调用replace。我的方法a允许使用单个调用,而b则更清楚地传达了预期的输入类型。replaceAll请求一个正则表达式,在其中具有特殊意义;使用已部分使用的普通替换仅使用替换而不是全部替换。
final String bar = foo.replaceAll("\\(?'([^']*)'\\)?", "$1");
// Output: UK, IT, DE
System.out.println("Naive:");
try {
    System.out.println("(("
            .replaceAll("(", "$"));
} catch (Exception ex) {
    System.out.println(ex);
}
System.out.println("\nPattern.quote:");
try {
    System.out.println("q: "+Pattern.quote("("));
    System.out.println("(("
            .replaceAll(Pattern.quote("("), "$"));
} catch (Exception ex) {
    System.out.println(ex);
}
System.out.println("\nPattern.quote+Matcher.quoteReplacement:");
try {
    System.out.println("q: "+Pattern.quote("("));
    System.out.println("qR: "+Matcher.quoteReplacement("$"));
    System.out.println("(("
            .replaceAll(Pattern.quote("("), Matcher.quoteReplacement("$")));
} catch (Exception ex) {
    System.out.println(ex);
}
Naive:
java.util.regex.PatternSyntaxException: Unclosed group near index 1
(

Pattern.quote:
q: \Q(\E
java.lang.IllegalArgumentException: Illegal group reference: group index is missing

Pattern.quote+Matcher.quoteReplacement:
q: \Q(\E
qR: \$
$$