String.split (".") Doesn't break my long string

I do the following:

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

problem: test2 has no elements. But there is a lot in test String . .

Any idea what the problem is?

+4
source share
2 answers

Note that public String [] split (String regex) accepts a regular expression .

You need to avoid special char . .

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

Now you say Java:

"Do not accept . As a special char . , Consider it a regular char . "

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


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

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

+18
source

The point . is a special regular expression character. This means matching anyone. You need to avoid the character that in Java is executed with \\ .

Once it is escaped, it will not be considered special and will match just like any other character.

So String[] test2 = test.split("\\."); gotta do the trick beautifully!

+10
source

All Articles