Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.split(".") is not splitting my long String

Tags:

java

I'm doing the following:

String test = "this is a. example";
String[] test2 = test.split(".");

the problem: test2 has no items. But there are many . in the test String.

Any idea what the problem is?

like image 555
gurehbgui Avatar asked Nov 27 '22 14:11

gurehbgui


1 Answers

Note that public String[] split(String regex) takes a regex.

You need to escape the special char ..

Use String[] test2 = test.split("\\.");

Now you're telling Java:

"Don't take . as the special char ., take it as the regular char .".

Note that escaping a regex is done by \, but in Java, \ is written as \\.


As suggested in the comments by @OldCurmudgeon (+1), you can use public static String quote(String s) that "Returns a literal pattern String for the specified String":

String[] test2 = test.split(Pattern.quote("."));

like image 71
Maroun Avatar answered Dec 13 '22 13:12

Maroun