String的replaceAll()方法和转义字符 [英] String's replaceAll() method and escape characters

查看:523
本文介绍了String的replaceAll()方法和转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该行

System.out.println("\\");

打印单个反斜杠( \ )。并且

prints a single back-slash (\). And

System.out.println("\\\\");

打印双反斜杠( \\ )。明白了!

prints double back-slashes (\\). Understood!

但为什么在以下代码中:

But why in the following code:

class ReplaceTest
{
    public static void main(String[] args)
    {
        String s = "hello.world";
        s = s.replaceAll("\\.", "\\\\");
        System.out.println(s);
    }
}

是输出:

hello\world

而不是

hello\\world

毕竟, replaceAll()方法正在替换一个点( \\。)( \\\\ )。

After all, the replaceAll() method is replacing a dot (\\.) with (\\\\).

有人可以解释这个?

推荐答案

使用正则表达式替换字符时,您可以使用反向引用,例如 \ n 使用匹配中的分组替换a。

When replacing characters using regular expressions, you're allowed to use backreferences, such as \1 to replace a using a grouping within the match.

但是,这意味着反斜杠是一个特殊字符,所以如果你实际上想要使用需要转义的反斜杠。

This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.

这意味着在Java字符串中使用它时需要实际转义两次。 (首先是字符串解析器,然后是正则表达式解析器。)

Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)

这篇关于String的replaceAll()方法和转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆