11

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";
Jonik
  • 77,494
  • 68
  • 254
  • 365
Programmer
  • 435
  • 2
  • 8
  • 25

5 Answers5

45

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 ..

Maroun
  • 91,013
  • 29
  • 181
  • 233
3

You must escape the dot.

String columnArray[] = a.split("\\.");
Arnaud Denoyelle
  • 28,245
  • 14
  • 82
  • 137
2

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

String[] columnArray = a.split("\\."); 
Aniket Thakur
  • 63,511
  • 37
  • 265
  • 281
1

While using special characters need to use the particular escape sequence with it.

'.' is a special character so need to use escape sequence before '.' like:

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

The next code:

   String input = "myValue.Folder.FolderCentury";
   String regex = "(?!(.+\\.))\\.";
   String[] result=input.split(regex);
   System.out.println(Arrays.toString(result));

Produces the required output:

[myValue.Folder, FolderCentury]

The regular Expression tweaks a little with negative look-ahead (this (?!) part), so it will only match the last dot on a String with more than one dot.

Tomas Narros
  • 13,317
  • 2
  • 38
  • 56