Hubabuba Hubabuba - 3 years ago 260
Java Question

Escape character before closing brascet is redundant

I need to match some digits between curly brackets in string, my regex look like this:

SNC{(\\\d*)}
.

After applying escape characters, I thought that regex should transform into
SNC\\\\{(\\\d*)\\\\}
, but Intellij's inspector is suggesting that escape backslashes before closing bracket is redundant so
SNC\\\\{(\\\d*)}
is enough. Why does it work?

Answer Source

In regex {m,n} is used as quantifier representing amount between m and n (inclusive). If you escaped first { like \{..} then regex engine will not treat rest of that subexpression as description of quantifier, so it is no longer special which allows us to skip escaping for } (although it is allowed, meaning your code will work, but as you see some IDEs consider it as unnecessary and warn you about it).

BTW same rule applies to \[...] but NOT to \(...) - regex always expects ) to be explicitly escaped if you want to treat it as literal, since (...) is used very often and having unescaped ) in regex like ( \( ( ...) ( ) ) ) could be very confusing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download