0

I'm solving this problem in my own way. I'm trying to split the file path into Drive, folders, and file name, all into an array.

Complete class. (Github)

The problem:

String regex = "\\";
String [] divisions = path.split (regex);

This gives me an java.util.regex.PatternSyntaxException. I looked up the wiki and found [\b]

String regex = "[\b]";
String [] divisions = path.split (regex);

This doesn't work. It doesn't throw an exception, nor does it split my file path based on backspace.

Input:

► Enter path -- 
C:\User\Admin\NekedGaben.jpg

Output:

→ Path = C:\User\Admin\NekedGaben.jpg
→ File name = C:\User\Admin\NekedGaben
→ Extension = .jpg

My questions:

  1. Why does "\\" throw an exception, while "[\b]" doesn't?
  2. Why doesn't the split() split the Path string?
2
  • What is \ in regex? (Not "\\", that is a String literal.) Commented Feb 2, 2015 at 17:19
  • You want to read the wiki more carefully: [\b] matches a backspace, not a backslash. Why would you ever want to match a backspace? I don't know, I've never needed to. But \b by itself matches a word boundary, and it can't mean that inside a character class, so its meaning arbitrarily changes to backspace. Commented Feb 2, 2015 at 23:11

2 Answers 2

6

You should use double escaping in Java regex, i.e.:

String regex = "\\\\";

Or use static Pattern.quote(String) method:

String regex = Pattern.quote("\\");
Sign up to request clarification or add additional context in comments.

Comments

2

Because \b is a single character, the compiler knows it, they're friends.

However backslash (\) is represented by \\ in Java, and \ is invalid regex, in order to escape it, you should use:

\\\\
↓ ↓
escaping

Solution:

  • Escape it as shown above
  • Don't escape, let Pattern#quote handle this for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.