How to escape a square bracket for Pattern compilation

后端 未结 4 1483
萌比男神i
萌比男神i 2020-12-03 10:16

I have comma separated list of regular expressions:

.{8},[0-9],[^0-9A-Za-z ],[A-Z],[a-z]

I have done a split on the comma. Now I\'m trying

4条回答
  •  暖寄归人
    2020-12-03 10:34

    For some reason, the above answer didn't work for me. For those like me who come after, here is what I found.

    I was expecting a single backslash to escape the bracket, however, you must use two if you have the pattern stored in a string. The first backslash escapes the second one into the string, so that what regex sees is \]. Since regex just sees one backslash, it uses it to escape the square bracket.

    \\] 
    

    In regex, that will match a single closing square bracket.

    If you're trying to match a newline, for example though, you'd only use a single backslash. You're using the string escape pattern to insert a newline character into the string. Regex doesn't see \n - it sees the newline character, and matches that. You need two backslashes because it's not a string escape sequence, it's a regex escape sequence.

提交回复
热议问题