//This source is a line read from a file
String src = "23570006,music,**,wu(),1,exam,\"Monday9,10(H2-301)\",1-10,score,";
//This sohuld be from a matcher.group() when Pattern.compile("\".*?\"")
String group = "\"Monday9,10(H2-301)\"";
src = src.replaceAll("\"", "");
group = group.replaceAll("\"", "");
String replacement = group.replaceAll(",", "#@");
System.out.println(src.contains(group));
src = src.replaceAll(group, replacement);
System.out.println(group);
System.out.println(replacement);
System.out.println(src);
我正在尝试替换 \"s
之间的 ","
以便我可以在后者使用 String.split()
。
但是上面的方法不起作用,结果是:
true
Monday9,10(H2-301)
Monday9#@10(H2-301)
23570006,music,**,wu(),1,exam,Monday9,10(H2-301),1-10,score,
但是当我将 src 字符串更改为
String src = "123\"9,10\"123";
String group = "\"9,10\"";
效果不错
true
9,10
9#@10
1239#@10123
字符串怎么了???
最佳答案
(
和 )
是正则表达式元字符;如果您想按字面意思匹配它们,则需要对其进行转义。
String group = "\"Monday9,10\\(H2-301\\)\"";
^ ^
之所以需要两个斜杠,是因为字符串字面量中的\
本身就是一个转义字符,所以"\\"
是一个长度为1的字符串,包含一个斜杠。
关于java - 为什么 String.replaceAll() 不适用于此字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2735003/