java 正则表达式替换

来源:互联网 发布:2017网络电视剧排行榜 编辑:程序博客网 时间:2024/05/22 09:02
一直一来遇到"替换为/" 的时候概念总是很模糊,今天要搞搞清楚。
System.out.println("/"".replace("/"", "///""));System.out.println("/"".replaceAll("/"", "/////""));System.out.println("/"".replaceAll("///"", "/////""));
需要注意的是:/在正则表达式里需要再转义一次,所以replaceAll的第二个参数变得很长。 但是最后一行为什么也是可以的,这个我就不明白了,查了javadoc(在james的引导下),发现有这样一段话: It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct. 此外还有,这样/这个符号在正则中如果什么都没有跟(没有转义),那么只是简单的引用后面那个字符; 配合上面那段文档也就是说,/+非字母字符 就等于 这个非字母字符(ie:/= 和 = 是一样),这就解释了 /"和"是一样的原因,哈哈。 搞了半天是javadoc没看仔细啊~。。。
原创粉丝点击