Why regex "\\[\\]" is redundant in Java?

Raining :

I want to match just the bracket [], in my code:

// #peekToken() -> String
do { ... } while (context.peekToken().matches("\\[\\]"));

the intellij says:

Intellij says about brackets

and the auto-fixing makes it into:

"\\[]"

Why are they the same?

Paul Lemarchand :

This is because the character "close bracket" ] is not a regular expression unless there was a bracket opened [ before. Therefore it is redundant to escape it \\], since Java is smart enough to know we are searching for the character itself in that case.

You can read the documentation for more informations on contexts where characters are percieved as regular-expressions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156610&siteId=1