Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Split a string on a backslash

Tags:

java

string

I have a path to a file stored as a string: "C:\\Users\\Owner\\Desktop\\foo.txt". I want to isolate just the "foo.txt" part, so I try to split the string on a backslash, like so "C:\\Users\\Owner\\Desktop\\foo.txt".split("\\"), then get the last element of the array. If I understand correctly, then the first backslash should escape the second, making it not a special character, so that the string would split on a backslash character. However, when I run the code, I get a java.util.regex.PatternSyntaxException thrown. What is the proper way to split on backslashes in java?

like image 353
Matthew Flynn Avatar asked May 19 '26 03:05

Matthew Flynn


2 Answers

The backslash is reserved, so you have to use a double-backslash like so:

filename.split("\\\\")

To make this solution work consistently across platforms, however, it would be better to use:

filename.split(Pattern.quote(File.separator))

Alternatively, as Dici pointed out, you could just do:

new File(filename).getName()
like image 189
Hans Brende Avatar answered May 20 '26 15:05

Hans Brende


Oh no... please don't start messing with Windows filenames. One thing you don't want is to have platform-dependent code. Rather than this, use standard Java library:

System.out.println(new File("C:\\Users\\Owner\\Desktop\\foo.txt").getName());

Finally, if you really had to parse the path manually, I would use File.separatorChar to make the code portable.

// hardcoded here for the example, but you would actually get it from somewhere
String path = "C:\\Users\\Owner\\Desktop\\foo.txt"; 

int i = path.lastIndexOf(File.separatorChar);
String last = i < 0 || i == s.length() ? "" : path.substring(i + 1);
System.out.println(last);

This is also less expensive than splitting a string since you're only interested in the last element.

like image 31
Dici Avatar answered May 20 '26 15:05

Dici