Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Java String return empty array? [duplicate]

Tags:

java

split

I have a String something like this

"myValue"."Folder"."FolderCentury";

I want to split from dot("."). I was trying with the below code:

String a = column.replace("\"", "");
String columnArray[] = a.split(".");

But columnArray is coming empty. What I am doing wrong here?

I will want to add one more thing here someone its possible String array object will contain spitted value like mentioned below only two object rather than three.?

columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
like image 999
Programmer Avatar asked Aug 29 '13 10:08

Programmer


2 Answers

Note that String#split takes a regex.

You need to escape the special char . (That means "any character"):

 String columnArray[] = a.split("\\.");

(Escaping a regex is done by \, but in Java, \ is written as \\).

You can also use Pattern#quote:

Returns a literal pattern String for the specified String.

String columnArray[] = a.split(Pattern.quote("."));

By escaping the regex, you tell the compiler to treat the . as the string . and not the special char ..

like image 178
Maroun Avatar answered Sep 24 '22 16:09

Maroun


split() accepts an regular expression. So you need to skip '.' to not consider it as a regex meta character.

String[] columnArray = a.split("\\."); 
like image 22
Aniket Thakur Avatar answered Sep 21 '22 16:09

Aniket Thakur