日期:2014-05-18  浏览次数:20730 次

遇到一个很奇怪的问题,java字符串的
本帖最后由 oACheng1 于 2014-01-09 10:21:53 编辑
我有一个字符串
比如 s = select * from abc[x][y][z]
x=de,y=fg,z=hi
现在需要替换字符串 我是用这种方法替换的,因为后面或许还有x,只替换第一个[x]
s=s.replaceFirst("["+"x"<这里是个变量,我在这先写死了>+"]",x);
问题出现了,在编码时,""是表示字符串的,中间应该变成粗体,他却是普通的字体,我以为就是个显示问题,就没有在意,写了个main方法测试时发现,"["根本就没有匹配,就是说,他没有起作用,只是替换了x而已,
而换成replace 后就一切恢复了正常,请问这是怎么回事,以前从来没有遇到过

------解决方案--------------------
   String  s="sd[dsd]88bb";
        System.out.println(s); 
        System.out.println(s.replace("[", "----")); 
        System.out.println(s.replaceFirst("\\[", "----"));


[ 和 ] 需要转移,replaceFirst方法的第一个参数匹配是正则。


/**
     * Replaces the first substring of this string that matches the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a> with the
     * given replacement.
     *
     * <p> An invocation of this method of the form
     * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
     * yields exactly the same result as the expression
     *
     * <blockquote><tt>
     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
     * compile}(</tt><i>regex</i><tt>).{@link
     * java.util.regex.Pattern#matcher(java.lang.CharSequence)
     * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
     * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
     *
     *<p>
     * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
     * replacement string may cause the results to be different than if it were
     * being t