Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing: [\/] (\ or / regex) correctly?

Tags:

java

regex

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?

like image 679
Mr. Adobo Avatar asked Apr 23 '13 22:04

Mr. Adobo


1 Answers

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 \\\\.

like image 182
arshajii Avatar answered Sep 20 '22 22:09

arshajii