public class C {
public static void main(String[] args) {
String str = "http://ratehis.taobao.com/user-rate-ffd223adfe0522a83770a7ee582fdf9b--detailed|1--goodNeutralOrBad|1--isarchive|true--timeLine|-211--receivedOrPosted|0--buyerOrSeller|0.htm#RateType";
String str1 = str.replaceAll("|", " ");
System.out.println(str1);
}
}原本是要将str中的"|"替换成空格,可是他却在每两个字符间插入了一个空格
输出的str1为
h t t p : / / r a t e h i s . t a o b a o . c o m / u s e r - r a t e - f f d 2 2 3 a d f e 0 5 2 2 a 8 3 7 7 0 a 7 e e 5 8 2 f d f 9 b - - d e t a i l e d | 1 - - g o o d N e u t r a l O r B a d | 1 - - i s a r c h i v e | t r u e - - t i m e L i n e | - 2 1 1 - - r e c e i v e d O r P o s t e d | 0 - - b u y e r O r S e l l e r | 0 . h t m # R a t e T y p e 不知道这事如何解决
public class C {
public static void main(String[] args) {
String str = "http://ratehis.taobao.com/user-rate-ffd223adfe0522a83770a7ee582fdf9b--detailed|1--goodNeutralOrBad|1--isarchive|true--timeLine|-211--receivedOrPosted|0--buyerOrSeller|0.htm#RateType";
String str1 = str.replaceAll("\\|", " ");
System.out.println(str1);
}
}不是String的bug,是你没看replaceAll怎么使用,也没看正则表达式怎么用。
这样也不会有问题e...这个怎么算是bug...?
你如果是想-str中的"|"替换成空格,
应该用:
replace('|',' ');
public class C {
public static void main(String[] args) {
String str = "http://ratehis.taobao.com/user-rate-ffd223adfe0522a83770a7ee582fdf9b--detailed|1--goodNeutralOrBad|1--isarchive|true--timeLine|-211--receivedOrPosted|0--buyerOrSeller|0.htm#RateType";
String str1 = str.replaceAll("[|]", " ");
System.out.println(str1);
}
}
replaceAll方法是通过正则来做的。
replaceAll(String regex, String replacement)
如果只是做普通的字符串替换的话,可以使用 replace 这个方法。如果不想用 replace 的话,那还是可以用 replaceAll 这个方法的,其中的特殊字符(一共有 15 个)
需要转义,如果不知道哪些字符需要转义的话,可以在字符串外面加上 Pattern.quote() 进行正则表达式
引用:str = str.replaceAll(Pattern.quote("|"), " ");需要注意的是 Pattern.quote 这个方法是 JDK 1.5 新增的方法,在 JDK 1.5 中还有一些 bug,如果
要用这个方法的话,建议使用 JDK 6 的版本。replaceAll 用这个方法进行替换时,不仅需要注意第一个参数,而且还得注意第二个参数,第二个参数是
替换后的字符,如果碰到 $ 和 \ 需要进行转义。另外说一下,replace 其内部实现也是依赖于正则表达式的,只不过其采用了正则表达式的字面模式。
应该用:
replace('|',' ');
要用str.replaceAll("\\|", " ");
这样试试,那个应该是转义字符,之前我也遇到过\,就是这样解决的
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */ while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}
System.out.println(str1);
replaceAll
public String replaceAll(String regex,
String replacement)使用给定的 replacement 字符串替换此字符串匹配给定的正则表达式的每个子字符串。
此方法调用的 str.replaceAll(regex, repl) 形式产生与以下表达式完全相同的结果: Pattern.compile(regex).matcher(str).replaceAll(repl)参数:
regex - 用来匹配此字符串的正则表达式
返回:
得到的 String
抛出:
PatternSyntaxException - 如果正则表达式的语法无效
从以下版本开始:
1.4
另请参见:
Pattern
唉,现在的年轻人,心浮气躁啊....