12

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
  • 80,077
  • 70
  • 264
  • 372
Programmer
  • 455
  • 2
  • 8
  • 25

5 Answers5

46

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
  • 94,125
  • 30
  • 188
  • 241
3

You must escape the dot.

String columnArray[] = a.split("\\.");
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
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
  • 66,731
  • 38
  • 279
  • 289
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,390
  • 2
  • 40
  • 56