`

当正则表达式碰上"$" 或"\"

阅读更多
在java中使用到正则表达式,比如String.replace, String.replaceAll,
String.replaceFirst,Pattern.compile等等的时候,你得小心了。

你可能收到一个异常。
类似下面的url描述的bug:


http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6325596


http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4689750


http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6280695



至此,你要为Sun的Bug埋单。
如果你要处理的字符串将在页面显示,你可以把他进行
    URL Encoding http://www.w3schools.com/TAGS/ref_urlencode.asp
.然后再继续使用。


i.e.
//replace all $ with %24;
private static String convertDollar(String source) {
		 StringBuffer result = new StringBuffer();
		 for(int index = 0; index < source.length(); index++) {
			 result.append(source.charAt(index) == '$' ? "%24" : source.charAt(index));    
         }
		 return result.toString();
    }
分享到:
评论
9 楼 captmjc 2009-10-11  
LZ是不是调用类似String.replaceAll(regex, replacement)的时候,replacement中包含'$'?
8 楼 Ihavegotyou 2009-10-10  
ningmenglovesoft 写道
当你split();方法的时候也要注意。。要不人那结果真不是你想要的

贴出你的java 版本(java -version),和事例代码、异常栈
7 楼 ningmenglovesoft 2009-10-10  
当你split();方法的时候也要注意。。要不人那结果真不是你想要的
6 楼 xanpeng 2009-10-10  
bdceo 写道
跟Jdk的版本还真有关系啊,我用1.6.x的写了几行测试,哎?没出现楼主的异常

还是有异常的
5 楼 ray_linn 2009-10-10  
sun该抄抄C#那个"@"号了吧
4 楼 Jackphone 2009-10-10  
呵呵,用转义字符,再加上转义字符的转义字符。
3 楼 bdceo 2009-10-09  
跟Jdk的版本还真有关系啊,我用1.6.x的写了几行测试,哎?没出现楼主的异常
2 楼 Ihavegotyou 2009-10-08  
Eastsun 写道
Java docs上已经说得很明白了:
引用
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; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.


你说的对。
但是还是要看jdk版本。
你看完那三个url也就明白那么回事。
1 楼 Eastsun 2009-10-08  
Java docs上已经说得很明白了:
引用
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; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

相关推荐

Global site tag (gtag.js) - Google Analytics