String.replaceAll 的问题

realfish 2004-11-05 12:09:46
public class Test {
public static void main(String[] args) {
String temp = "$12345";
System.out.println(temp.replaceAll("$","0"));
}

}


为什么结果是$123450而不是我想要的012345;
用replace('$','0');就可以是012345?
...全文
154 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
fog628 2004-11-05
  • 打赏
  • 举报
回复
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
上面的是String类replaceAll的代码,"$"在regular-expression(一个参数) 只是代表一行的结尾,用
"\\p{Punct}"代替"$"(要双"\\",和C一样)
public class Test {
public static void main(String[] args) {
String temp = "$12345";
System.out.println(temp.replaceAll("\\p{Punct}","0"));
}

}
PoemCode 2004-11-05
  • 打赏
  • 举报
回复
又学到了一点儿
haroyy 2004-11-05
  • 打赏
  • 举报
回复
String.replaceAll(String regex, String replacement);
regex是正则表达式
realfish 2004-11-05
  • 打赏
  • 举报
回复
treeroot(根根)
temp.replaceAll("\\$","0"));

$需要转义
可以的
dreamno 2004-11-05
  • 打赏
  • 举报
回复
转义哦。
treeroot 2004-11-05
  • 打赏
  • 举报
回复
在正则表达式中$表示一行的结尾
表许用\$转义才表示$字符
但是\又是字符串的转义字符,所以又要对它转义\\
结果就是 "\\$",这里经过了两次转义
treeroot 2004-11-05
  • 打赏
  • 举报
回复
temp.replaceAll("\\$","0"));

$需要转义
tomuno 2004-11-05
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
String temp = "$1234".substring(1,("$1234".length()-1));
System.out.println(temp);
}

}
treeroot 2004-11-05
  • 打赏
  • 举报
回复
用 replaceAll("\$","0")
lenoli 2004-11-05
  • 打赏
  • 举报
回复
就是就是,楼上正解
loverisyour 2004-11-05
  • 打赏
  • 举报
回复
replaceAll只能替换一些基本的字符,对特殊的字符它是不能替换的,结果也没什么规律。

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧