模式中的冗余转义字符 [英] Redundant escape character in Pattern
问题描述
我正在尝试以下代码并且它打印为false。
我原本预计这会打印出来。
另外,Pattern.Compile()statemenet给出了一个警告'冗余转义字符'。
有人可以帮助我,为什么这不会返回真实,为什么我会看到警告。
I am trying out the following code and it's printing false. I was expected that this would print true. In addition , the Pattern.Compile() statemenet , gives a warning 'redundant escape character'. Can someone please help me as to why this is not returning true and why do I see a warning.
public static void main(String[] args) {
String s = "\\n";
System.out.println(s);
Pattern p = Pattern.compile("\\\n");
Matcher mm = p.matcher(s);
System.out.println(mm.matches());
}
推荐答案
s =\\ n
表示您为变量 s $指定反斜杠和
n
c $ c>,它包含两个字符的序列, \
和 n
。
The s="\\n"
means you assign a backslash and n
to the variable s
, and it contains a sequence of two chars, \
and n
.
Pattern.compile(\\\ n)
表示你定义一个正则表达式模式 \ n
匹配换行符。因此,此模式将与变量 s
中的字符串不匹配。
The Pattern.compile("\\\n")
means you define a regex pattern \n
that matches a newline char. Thus, this pattern won't match the string in variable s
.
冗余转义警告与事实上你在C字符串文字中使用三个反斜杠:两个反斜杠定义一个文字反斜杠,第三个是冗余的,即有一个文字 \
然后换行转义序列\ n
,这意味着文字反斜杠(在文字中用2个反斜杠定义)是多余的,可以删除。
The redundant escape warning is related to the fact you are using triple backslash in the C string literal: the two backslashes define a literal backslash and the third one is redundant, i.e. there is a literal \
and then a newline escape sequence "\n"
, and that means the literal backslash (defined with 2 backslashes in the literal) is redundant and can be removed.
这篇关于模式中的冗余转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!