Java string string splitting returns empty array?

I have a String something like this

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

I want to separate from the period ("."). I tried using the code below:

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

But columnArray getting empty. What am I doing wrong here?

I want to add one more thing: someone her possible String array object will contain a spitted value, as indicated below, only two objects, not three.?

 columnArray[0]= "myValue"."Folder"; columnArray[1]= "FolderCentury"; 
+4
source share
5 answers

Note that String # split accepts a regular expression .

You need to avoid special char . (This means "Any character"):

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

(The regex escape is performed \ , but in Java \ written as \\ ).

You can also use Pattern # quote :

Returns a string literal String for the specified string.

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

By expressing a regular expression, you tell the compiler to consider . like String . , not a special char . .

+25
source

You must avoid the point.

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

split () accepts a regular expression. So you need to skip the "." not to consider it a metacharacter of a regular expression.

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

The following 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 changes a bit with a negative appearance (this part (?!) ), So it will only correspond to the last point in the line with more than one point.

+1
source

When using special characters, you must use a specific escape sequence with it.

'' is a special character, so you must use the escape sequence before '.' as:

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

Source: https://habr.com/ru/post/1499581/


All Articles