0

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

Community
  • 1
  • 1
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • Just as a side note: make sure you fully understand your requirements; like: will your input contain different file separators; or will they be uniform; or on the other hand: will this code run on *one* specific platform; or is it supposed to run on many different ones? (and yes, I understand that this has going to answer your question) – GhostCat Nov 26 '16 at 20:10
  • @GhostCat Originally what i want to do is get the current directory of the `.jar` file which is tricky . It works if the user starts it with double click but it doesn't work if it starts it from command prompt , so i made a special method to do it . AFAIK Testing it on Windows the path is giving an extra `/` on the beginning that's why i need to use this regex . I have added and an answer ( http://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java#7603444 ) . If you know a better way i will be very glad :) It is intended to work on multiple platforms. – GOXR3PLUS Nov 26 '16 at 20:14

1 Answers1

0

Well the error was :

By simply using \\ it was replaced by \ so i had only the special character.

The solution is to use \\\\ so it is replaced by \\ and the first \ treats the second \ as a character and not a special character.

Leaving this solution here in case somebody has the same problem..

GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • Well, your problem has actually been asked and answered here before. And as there are no upvotes around (and probably no coming) ... you might consider to simply delete your question. – GhostCat Nov 26 '16 at 20:16