“Invalid escape sequence (valid ones are \b \t \n \f \r \” \' \\ )" syntax error

后端 未结 3 660
夕颜
夕颜 2021-01-14 13:15

I wrote code for matching filepath which have extenstion .ncx ,

 pattern = Pattern.compile(\"$(\\\\|\\/)[a-zA-Z0-9_]/.ncx\");
 Matcher matcher = pattern.math         


        
相关标签:
3条回答
  • 2021-01-14 13:44

    try this

    $(\\|\\/)[a-zA-Z0-9_]/.ncx
    
    0 讨论(0)
  • 2021-01-14 13:45
    Pattern p = Pattern.compile("[/\\\\]([a-zA-Z0-9_]+\\.ncx)$");
    Matcher m = p.matcher("\\sample.ncx");
    if (m.find())
    {
      System.out.printf("The filename is '%s'%n", m.group(1));
    }
    

    output:

    The filename is 'sample.ncx'
    

    $ anchors the match to the end of the string (or to the end of a line in multiline mode). It belongs at the end of your regex, not the beginning.

    [/\\\\] is a character class that matches a forward-slash or a backslash. The backslash has to be double-escaped because it has special meaning both in a regex and in a string literal. The forward-slash does not require escaping.

    [a-zA-Z0-9_]+ matches one or more of the listed characters; without the plus sign, you were only matching one.

    The second forward-slash in your regex makes no sense, but you do need a backslash there to escape the dot--and of course, the backslash has to be escaped for the Java string literal.

    Because I switched from the alternation (|) to a character class for the leading slash, the parentheses in your regex were no longer needed. Instead, I used them to capture the actual filename, just to demonstrate how that's done.

    0 讨论(0)
  • 2021-01-14 13:51

    In java \ is a reserved character for escaping. so you need to escape the \.

    pattern=Pattern.compile("$(\\\\|\\/)[a-zA-Z0-9_]/.ncx");
    
    0 讨论(0)
提交回复
热议问题