Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PatternSyntaxException: Unexpected internal error near index 1 for `.split(File.separator)` under windows

Tags:

java

The following snippet works fine under linux but gives me error under windows (which is very weird since jvm/jdk is supposed to be OS-agnostic).

  File f = ... 
  String[] split = f.getPath().split(File.separator);

Here is the error:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
        at java.util.regex.Pattern.error(Unknown Source)
        at java.util.regex.Pattern.compile(Unknown Source)
        at java.util.regex.Pattern.<init>(Unknown Source)
        at java.util.regex.Pattern.compile(Unknown Source)
        at java.lang.String.split(Unknown Source)
        at java.lang.String.split(Unknown Source)

any idea what is wrong?

like image 461
Daniel Avatar asked Dec 07 '15 08:12

Daniel


2 Answers

You should consider using the Path class introduced with java.nio. It works even if you mix the separators. This code:

    Path path = Paths.get("c:\\a\\with spaces/b");

    for(Iterator<Path> it= path.iterator(); it.hasNext();) {
        System.out.println(it.next());
    }

prints:

a
with spaces
b
like image 70
Eduardo Javier Huerta Yero Avatar answered Nov 14 '22 08:11

Eduardo Javier Huerta Yero


The problem is that the backslash is a special character using regexes (escape character for other special characters). You should use

String[] split = f.getPath().split("\\\\");

in order to split by the sign \.


I see the problem you have if you want to keep this platform independant. In that case you could do something like this:

String splitter = File.separator.replace("\\","\\\\");
String[] split = abc.split(splitter);
like image 44
ParkerHalo Avatar answered Nov 14 '22 07:11

ParkerHalo