可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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()); }
回答1:
The s="\\n" means you assign a backslash and n to the variable s, and it contains a sequence of two chars, \ and n.
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.
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.
回答2:
Because "\\n" evaulates to backslash \\ and the letter n while "\\\n" evaluates to a backslash \\ and then a newline \n.
回答3:
Your source s has two characters, '\' and 'n', if you meant it would be \ followed by a line break then it should be "\\\n"
Pattern has two characters '\' and '\n' (line break) and \ the escape characher is not needed, hence warning. If you meant \ followed by line break it should be "\\\\\n" (twice \ to escape it for regex and then \n).
String s = "\\\n"; System.out.println(s); Pattern p = Pattern.compile("\\\\\n"); Matcher mm = p.matcher(s); System.out.println(mm.matches());
回答4: