I want to match forward slash / or back slash \ in particular string for e.g.:
1. Hi/Hello/Bye/
2. Hi\Hello\Bye\
3. Hi\Hello/Bye\
4. HiHelloBye
In the given strings only the last record should not be matched because it does not contain either / or \.
What I am using
if (strFile.matches(".*//.*"))
{
//String Matches.
}
else
{
//Does not match.
}
This matches for forward slash / only. I don’t know how to write regex for both slash (for OR condition).
The “character” you’re looking to match would be:
duplicating the backslash first for the string then again for the regex.
This is perhaps the nastiest bit of regexes when you need to use backslashes in languages that also use the backslash for escaping strings.
The Java compiler sees the string
"\\\\"in the source code and actually turns that into"\\"(since it uses\as an escape character).Then the regular expression sees that
"\\"and, because it also uses\as an escape character, will treat it as a single\character.Once all that reduction is done, you have specified a character class consisting of both slashes and, if the character in question matches either of them, it returns true.
The following code shows this in action:
and it outputs:
'Hi/Hello/Bye/': true 'Hi\Hello\Bye\': true 'Hi\Hello/Bye\': true 'HiHelloBye': false