Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string with "\" in Android

I am trying to split a string with "\" but its not working for me, the string contains alpha numeric data and some Japaneses characters..

Here is the code i am trying

String [] folder = null;
String [] files= null;
for (int i =0; i<listFile_Names.size();i++) 
{

String  filesList = listFile_Names.get(i);
filesList = filesList.substring(1);
Log.v("Fullpath",filesList );
try{
String[] parts = filesList.split("\\");
folder[i] = parts[0]; 
files[i] = parts[1]; 
}
catch(Exception e){
e.printStackTrace();

}
}
for(int j=0; j< folder.length; j++)
{
Log.v("Folders", folder[j].toString());
Log.v("Files", files[j].toString());

}

Here is what LogCat Says

06-11 11:19:03.300: V/Fullpath(14600): A40-002(D155AX-8_DUAL仕様チェックシート)\sheet001.html
06-11 11:19:03.300: W/System.err(14600): java.util.regex.PatternSyntaxException: Unrecognized backslash escape sequence in pattern near index 1:
06-11 11:19:03.300: W/System.err(14600): \
06-11 11:19:03.300: W/System.err(14600):  ^
06-11 11:19:03.300: W/System.err(14600):    at java.util.regex.Pattern.compileImpl(Native Method)
06-11 11:19:03.300: W/System.err(14600):    at java.util.regex.Pattern.compile(Pattern.java:400)
06-11 11:19:03.300: W/System.err(14600):    at java.util.regex.Pattern.<init>(Pattern.java:383)
06-11 11:19:03.300: W/System.err(14600):    at java.util.regex.Pattern.compile(Pattern.java:374)
06-11 11:19:03.300: W/System.err(14600):    at java.lang.String.split(String.java:1842)
06-11 11:19:03.300: W/System.err(14600):    at java.lang.String.split(String.java:1823)
06-11 11:19:03.300: W/System.err(14600):    at jp.co.komatsu.android.xlez.webservice.AsynTaskGetUpdatedFiles.doInBackground(AsynTaskGetUpdatedFiles.java:202)
like image 985
Addy Avatar asked Jun 11 '14 06:06

Addy


2 Answers

Since the backslash has an special meaning in regex you have to escape it twice:

String[] parts = filesList.split("\\\\");

This is because Java interprets the string literal \\ as \. You can easily see this executing this code:

String s = "123\\";
System.out.println(s); // Output: 123\
like image 199
Christian Tapia Avatar answered Nov 11 '22 20:11

Christian Tapia


I believe you need to do 4 backslashes, each one of the 2 you are trying to represent needs to be escaped.

String[] arrA = str.split("\\\\");
like image 44
Aniruddha Avatar answered Nov 11 '22 18:11

Aniruddha