JAVA中的String某个字符替换

在java语言中,需要将String字符串中的所有"'"转换成 "\'",也就是单引号前增加一个"\"
要求在jdk1.4.2和jdk 1.5下都能正常运行

[b]问题补充:[/b]
问题来由是这样的,我们开发使用webshpere,我是后台开发人员,测试机was jdk为1.4.2,之前我这样写的
[code="java"]
String columnValue = this.getColumnValue(columnName).toString().replaceAll("\'", "\'");
[/code]
结果在was 的jdk 1.4.2下没问题,发到项目上,项目使用的was 的jdk 1.5
结果没有该方法
为什么要有那么多的"\"呢,我不大清楚

因为replace方法内部是使用正则表达式的

lz可以看看下面这段代码
[code="java"]
public Matcher appendReplacement(StringBuffer sb, String replacement) {

    // If no match, return error
    if (first < 0)
        throw new IllegalStateException("No match available");

    // Process substitution string to replace group references with groups
    int cursor = 0;
    String s = replacement;
    StringBuffer result = new StringBuffer();

    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++;

            // Capture the largest legal group string
            boolean done = false;
            while (!done) {
                if (cursor >= replacement.length()) {
                    break;
                }
                int nextDigit = replacement.charAt(cursor) - '0';
                if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
                    break;
                }
                int newRefNum = (refNum * 10) + nextDigit;
                if (groupCount() < newRefNum) {
                    done = true;
                } else {
                    refNum = newRefNum;
                    cursor++;
                }
            }

            // Append group
            if (group(refNum) != null)
                result.append(group(refNum));
        } else {
            result.append(nextChar);
            cursor++;
        }
    }

    // Append the intervening text
    sb.append(getSubSequence(lastAppendPosition, first));
    // Append the match substitution
    sb.append(result.toString());

    lastAppendPosition = last;
return this;
}

[/code]
注意 if (nextChar == '\')
你该知道了吧~

[code="java"]String a = "a'b'c'd''f'";
System.out.println(a.replaceAll("'", "\\'"));[/code]

试试用UniCode替换

[code="java"]
String a = "a'b'c'd''f'";

System.out.println(a.replaceAll("'", "\\'"));
[/code]
对1楼进行了细微修改

[color=blue] 直接用1楼的方法可以的呀!

难道就问这么简单的问题?是不是问题没描述清楚?
[/color]

……

主要是因为"\" 是转义符的问题

[color=blue]2个\相当于1个\。因为是\转义字符[/color]

[color=blue]

"\'" ( 转义字符)

"\'" ( 第一个\是转义字符,将第2个\,转义为普通的\ )

[/color]

" \ " = \ ;
" \' "= ' ;
自己想想把