I'm trying to write a regex that matches either \
or /
.
No matter in what order I write it:
[//\]
or
[/\\]
It is somehow escaping either my square bracket or my forward slash. What's the correct way of showing this particular case?
Yes, you are escaping the closing bracket in the second regex, and the first one won't even compile as a string. You want
"[/\\\\]"
Both of your regex in the question are correct plain regex. However, since the regex is specified inside a Java string literal, to specify a \
, you need to escape it \\
. Therefore, we end up with "[/\\\\]"
or "[\\\\/]"
.
In summary, to correctly specify \
in the regex, we must escape it \\
. And to correctly specify \\
in Java string literal, we must add on another layer of escaping \\\\
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With