日期:2014-05-20  浏览次数:20737 次

使用replaceAll时遇到的奇怪问题,请大家一起来讨论一下
以下程序会出现
public   class   test   {

public   static   void   main(String[]   args)   {
String   dd= "dddddddddddd   varstatus   aaaaaaaaaaaaaa ";
dd=dd.replaceAll( "varstatus ",   "50$   sss ");
System.out.print(dd);
}
}
异常信息如下
Exception   in   thread   "main "   java.lang.IllegalArgumentException:   Illegal   group   reference
at   java.util.regex.Matcher.appendReplacement(Unknown   Source)
at   java.util.regex.Matcher.replaceAll(Unknown   Source)
at   java.lang.String.replaceAll(Unknown   Source)

如果我把程序修改如下就正常了

public   class   test   {

public   static   void   main(String[]   args)   {
String   dd= "dddddddddddd   varstatus   aaaaaaaaaaaaaa ";
dd=dd.replaceAll( "varstatus ",   "50%   sss ");
System.out.print(dd);
}
}
  仔细看就是一个‘%’的问题

------解决方案--------------------
// The first number is always a group
int refNum = (int)replacement.charAt(cursor) - '0 ';
if ((refNum < 0)||(refNum > 9))
throw new IllegalArgumentException(
"Illegal group reference ");
------解决方案--------------------
看看源代码就可以了对 $ 由处理的
while (cursor < replacement.length()) {
char nextChar = replacement.charAt(cursor);
if (nextChar == '\\ ') {
cursor++;
nextChar = replacement.charAt(cursor);
result.append(nextChar);
cursor++;
} else if (nextChar == '$ ') {
// Skip past $
cursor++;

// The first number is always a group
int refNum = (int)replacement.charAt(cursor) - '0 ';
if ((refNum < 0)||(refNum > 9))
throw new IllegalArgumentException(
"Illegal group reference ");
cursor++;