Is it possible to break the line around "." in java?

When I try to break the line around the occurrence of "." The split method returns an array of strings with a length of 0. When I split the occurrences of "a", it works fine. Does anyone know why? Is it divided not to work with punctuation marks?

+4
source share
2 answers

split accepts a regular expression. Try split("\\.") .

+14
source
 String a = "a.jpg"; String str = a.split(".")[0]; 

This will throw an ArrayOutOfBoundException because split accepts the arguments regex and "." is a reserved character in a regular expression representing any character. Instead, we should use the following statement:

 String str = a.split("\\.")[0]; //Yes, two backslashes 

When the code compiles, the regular expression is called "\.", Which we want it to be

Here is the link of my old blog post if you are interested: http://junxian-huang.blogspot.com/2009/01/java-tip-how-to-split-string-with-dot.html

+2
source

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


All Articles