Redian新闻
>
why doesn't replaceAll work?
avatar
why doesn't replaceAll work?# Java - 爪哇娇娃
m*r
1
String foo = '\' + '\';
foo.replaceAll("\\\\", "\\");
would cause an indexOutOfBounds exception.... i don't understand.
avatar
Q*g
2
看API啊。
我猜你是想要把两个backslashes换成一个是吧?应该这么写:
String foo = "\\" + "\\";
foo.replaceAll("\\\\\\\\", "\\\\");
replaceAll的第一个参数是regular expression。regular expression里
要用两个backslash '\\' 表示单个字符 '\'。然后因为你在java里头写字符串
常量也是'\\'表示一个'\'。所以第一个参数需要一共8个'\'。
第二个参数里头'\'也是有特殊含义的,所以也是。。。。
Note that backslashes (\) and dollar signs ($) in the replacement
string may cause the results to be different than if it were being
treated as a literal replacement string. Dollar signs may be
treated as references to captured subs

【在 m****r 的大作中提到】
: String foo = '\' + '\';
: foo.replaceAll("\\\\", "\\");
: would cause an indexOutOfBounds exception.... i don't understand.

avatar
A*o
3

'\' + '\' --> '\' + "" + '\'

【在 m****r 的大作中提到】
: String foo = '\' + '\';
: foo.replaceAll("\\\\", "\\");
: would cause an indexOutOfBounds exception.... i don't understand.

avatar
m*r
4
i got the first "\\\\\\\\", but thought the second part was just a normal
java string. anyway, thx, it works now.

【在 Q**g 的大作中提到】
: 看API啊。
: 我猜你是想要把两个backslashes换成一个是吧?应该这么写:
: String foo = "\\" + "\\";
: foo.replaceAll("\\\\\\\\", "\\\\");
: replaceAll的第一个参数是regular expression。regular expression里
: 要用两个backslash '\\' 表示单个字符 '\'。然后因为你在java里头写字符串
: 常量也是'\\'表示一个'\'。所以第一个参数需要一共8个'\'。
: 第二个参数里头'\'也是有特殊含义的,所以也是。。。。
: Note that backslashes (\) and dollar signs ($) in the replacement
: string may cause the results to be different than if it were being

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。