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

The following snippet works fine under linux, but gives me an error under windows (which is very strange, since jvm / jdk is assumed by 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?

+4
source share
1 answer

The problem is that the backslash is a special character using regular expressions (an escape character for other special characters). You have to use

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

to break the sign \.


I see your problem if you want this platform to be independent. In this case, you can do something like this:

String splitter = File.separator.replace("\\","\\\\");
String[] split = abc.split(splitter);
+8
source

Source: https://habr.com/ru/post/1618857/


All Articles