954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

String.split("\\"); throws PatternSyntaxException?

String line = "Extracting from E:\\Junk\\morejunk\\file.txt";
	System.out.println(line);	//prints:    Extracting from E:\Junk\morejunk\file.txt
		
	String[] splitPath = line.split("\\");	//exception thrown here
	String folder = splitPath[splitPath.length-2];
		
	System.out.println(folder);
Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1

My objective is to always print the folder containing the file being extracted (morejunk in this case).

Any suggestions why it wont accept "\\" as a pattern which is correctly syntaxed?

TheWhite
Junior Poster
174 posts since May 2008
Reputation Points: 72
Solved Threads: 6
 

String[] splitPath = line.split("\\\\");

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

hmm... well thats funny..

You are correct.. Here I specified the cmd with 2 \'s, but ur way also works when line is given as a paramater, using only 1 \'s.

I guess java automatically throws in another \ on its own every time it sees only 1 \ so \\\\ works.

Thank you.

TheWhite
Junior Poster
174 posts since May 2008
Reputation Points: 72
Solved Threads: 6
 

I suposse, in "\\\\" are three kinds of character, one original \ and two meta characters in order m2,m1,m2,orig.

quuba
Posting Pro
573 posts since Nov 2008
Reputation Points: 123
Solved Threads: 106
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You