Redundant escape character in Pattern

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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:

\\b" matches a word boundary.

Refer : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!