ReplaceFirst

ReplaceFirst
ReplaceFirst

java的replaceFirst和\(反斜杠)replace、replaceAll和

replaceFirst的区别

repalce

函数原型为:

replace(CharSequence target, CharSequence replacement)

这个函数的功能就是将某个String中的字符串target替换成为字符串replacement,不涉及正则表达式。但是值得注意的是replace是全部替换。

repalceAll

函数的原型为:

String replaceAll(String regex,String replacement)

函数的功能和replace类似,也是完全替换,但是regex是正则表达式(当然也可以是字符串,正则表达式的一种)。

str.replaceAll(regex, repl)

相当于:

https://www.360docs.net/doc/4415900931.html,pile(regex).matcher(str).replaceAll(repl)

repalceFirst

类似replaceAll,但是只替换一次。

反斜杠\和正则表达式

我们知道在字符串中\需要用来“\\”表示,例如System.out.println( "\\" ) ;只打印出一个"\"。正则表达式中也用\表示转义。\在正则表示式中也作为转义字符使用,所以在正则表达式中"\\\\"才表示一个反斜杠,即"\"。

对于replaceFirst和replaceAll中的replacement,如果其中包含\的话,将作为转义字符看待,java api中的说明如下:

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.replaceAll. Use

Matcher.quoteReplacement(https://www.360docs.net/doc/4415900931.html,ng.String) to suppress the special meaning of these characters, if desired.

当我们利用repalceFirst或者replaceAll替换的时候,如果replacement中含有

\,替换的结果中的\的个数会减半,这往往是我们不希望看到的。我们可以先将

replacement中的\替换为\\,即replacement.replace("\\","\\\\")。

相关主题
相关文档
最新文档