I want to do what the title says , although i know how it can be done using the code below:
(Where local
is a variable which represents a path):
String path = ( local.startsWith(File.separator) || local.startsWith("/") || local.startsWith("\\"))
? local.substring(File.separator.length(), local.length())
: local;
I need to convert the above to regex expression so i am using:
path = local.replaceFirst("[" + File.separator + "/\\]", "");
Coming from xml schema
where i was using regex expressions and looking on tutorials here it seems to me that it must work but it doens't at all, i get this error ->:
java.util.regex.PatternSyntaxException: Unclosed character class near index 4
[\/\]
^
If i change the code to the below,it works:
local.replaceFirst("[" + File.separator + "/\\Q \\ \\E]", "");
Here is saying that \
is a special character but:
There are two ways to force a metacharacter to be treated as an ordinary character:
- precede the metacharacter with a backslash, or
- enclose it within \Q (which starts the quote) and \E (which ends it).
This question was also read : Forward slash in Java Regex