Invalid escape sequence

后端 未结 3 1425
既然无缘
既然无缘 2021-01-23 21:59

I would like to filter out all words containing 1 number and 3 capital letters with a total length of 4. See my example here: http://gskinner.com/RegExr/?32taa

A         


        
相关标签:
3条回答
  • 2021-01-23 22:09

    In Java, you need to escape the backslash with an extra backslash, when representing the pattern in string.

    So, \b should be \\b, and \d should be \\d.

    0 讨论(0)
  • 2021-01-23 22:10

    Regex don't go well with String...

    So u need to use \\d instead of \d

    - When you write \ java expects either n or b or t or a and few others... after it, but when you give d it gets the shock of its life, and think what the hell.. i don't know nothing about \d, So we need to tell java that \ should be taken literally by it instead of expecting it as escape character.

    - In the case of . (dot) it becomes even more complicated, when you give "." java takes it literally but its a regex so you need to make it look like that so you prefix it with \, so it becomes \. , now again the same problem as the earlier one begins as now java accepts n or b etc after \ but it gets a ".", so we again prefix it with another \, so now it becomes \\.

    0 讨论(0)
  • 2021-01-23 22:14

    Your code has two issues:

    • Your pattern is wrong, as it allows more digits - see http://regexr.com?32u3e

    • Java requires double escape slashes...

    Use regex pattern

    \\b(?=[A-Z]*\\d[A-Z]*\\b)[A-Z\\d]{4}\\b
    
    0 讨论(0)
提交回复
热议问题