Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split the string in java

Tags:

java

string

split

how to split the string in java in Windows? I used Eg.

String directory="C:\home\public\folder";
String [] dir=direct.split("\");

I want to know how to split the string in eg. In java, if I use "split("\")" , there is syntax error.

thanks

like image 760
sudo Avatar asked Aug 07 '26 00:08

sudo


2 Answers

split() function in Java accepts regular expressions. So, what you exactly need to do is to escape the backslash character twice:

String[] dir=direct.split("\\\\");

One for Java, and one for regular expressions.

like image 170
Eser Aygün Avatar answered Aug 09 '26 13:08

Eser Aygün


The syntax error is caused because the sing backslash is used as escape character in Java.

In the Regex '\' is also a escape character that why you need escape from it either.

As the final result should look like this "\\\\".

But You should use the java.io.File.separator as the split character in a path.

String[] dirs = dircect.split(Pattern.quote(File.separator));

thx to John

like image 27
Damian Leszczyński - Vash Avatar answered Aug 09 '26 12:08

Damian Leszczyński - Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!