为什么String.replaceAll()不能在这个String上工作? [英] Why String.replaceAll() don't work on this String?

查看:120
本文介绍了为什么String.replaceAll()不能在这个String上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    //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()后者。

I'm trying to replace the "," between \"s so I can use String.split() latter.

但上述情况不起作用,结果是:

But the above just not working , the result is:

true  
Monday9,10(H2-301)  
Monday9#@10(H2-301)  
23570006,music,**,wu(),1,exam,Monday9,10(H2-301),1-10,score,

但当我将src字符串更改为

but when I change the src string to

 String src = "123\"9,10\"123";  
 String group = "\"9,10\"";

运作良好

true  
9,10  
9#@10  
1239#@10123

字符串是什么问题???

What's the matter with the string???

推荐答案

是正则表达式元字符;如果你想要按字面意思匹配它们,则需要对它们进行转义。

( and ) are regex metacharacter; they need to be escaped if you want to match it literally.

String group = "\"Monday9,10\\(H2-301\\)\"";
                            ^        ^

你需要两个斜杠的原因是因为字符串文字中的 \ 本身就是一个转义字符,所以\\是一个长度为1的字符串,包含斜杠。

The reason why you need two slashes is that because \ in a string literal is itself an escape character, so "\\" is a string of length 1 containing a slash.

这篇关于为什么String.replaceAll()不能在这个String上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆