The spelling: [\ /] (\ or / regex) is correct?

I am trying to write a regular expression that matches either \ or / .

Regardless of the order in which I write it:

 [//\] 

or

 [/\\] 

It somehow eludes my square bracket or my slash. What is the correct way to show this particular case?

+7
source share
1 answer

Yes, you avoid closing brackets in the second regular expression, and the first will not even compile as a string. Do you want to

 "[/\\\\]" 

Both of your regular expressions in the question are the correct regular expression. However, since the regular expression is specified inside the Java string literal to indicate \ , you need to avoid it \\ . Therefore, in the end we get "[/\\\\]" or "[\\\\/]" .

In conclusion, to correctly specify \ in a regular expression, we need to avoid it \\ . And in order to correctly indicate \\ in the Java string literal, we must add \\\\ to another level of escaping.

+10
source

All Articles