Why does this Java regex cause “illegal escape character” errors?

前端 未结 6 1844
别那么骄傲
别那么骄傲 2020-11-27 21:28

I\'m working on a solution to a previous question, as best as I can, using regular expressions. My pattern is

\"\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-         


        
相关标签:
6条回答
  • 2020-11-27 21:49

    I think you need to add the two escaped shortcuts into character classes. Try this: "[\d]{4}[\w]{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"

    --Good Luck.

    0 讨论(0)
  • 2020-11-27 21:55

    Have you tried this?

    \\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}
    
    0 讨论(0)
  • 2020-11-27 22:00

    Assuming this regex is inside a Java String literal, you need to escape the backslashes for your \d and \w tags:

    "\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"
    

    This gets more, well, bonkers frankly, when you want to match backslashes:

    public static void main(String[] args) {        
        Pattern p = Pattern.compile("\\\\\\\\"); //ERM, YEP: 8 OF THEM
        String s = "\\\\";
        Matcher m = p.matcher(s);
        System.out.println(s);
        System.out.println(m.matches());
    }
    
    \\ //JUST TO MATCH TWO SLASHES :(
    true
    
    0 讨论(0)
  • 2020-11-27 22:01

    Did you try "\\d" and "\\w"?

    -edit- Lol I posted the right answer and get down voted and then I notice that stackoverflow escapes backslashes so my answer appeared wrong :)

    0 讨论(0)
  • 2020-11-27 22:06

    all you need to do is to put

     *\
     ex: string ex = 'this is the character: *\\s';
    

    before your invalid character and not 8 \ !!!!!

    0 讨论(0)
  • 2020-11-27 22:13

    What about the following: \\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}

    0 讨论(0)
提交回复
热议问题