Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The split() method in Java does not work on a dot (.) [duplicate]

Tags:

java

string

split

People also ask

Why split is not working for dot in Java?

If you want to split String on the dot you need to escape dot as \\. instead of just passing "." to the split() method. Alternatively, you can also use the regular expression [.] to split the String by a dot in Java.

Can we split by DOT in Java?

To split a string with dot, use the split() method in Java. str. split("[.]", 0);

What does split () does in Java?

The split() method divides the string at the specified regex and returns an array of substrings.

Why is my split function not working?

The SPLIT function belongs to VBA. It isn't part of Excel because it returns an array. Spreadsheets show elements of arrays in different cells. Therefore the result of the SPLIT function can't be shown in a single cell which, Excel being unable to display the result, would render the function itself useless.


java.lang.String.split splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").


The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

Try:

String words[]=temp.split("\\.");

The method is:

String[] split(String regex) 

"." is a reserved char in regex


The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\."). You need a double backslash, the second one escapes the first.


\\. is the simple answer. Here is simple code for your help.

while (line != null) {
    //             
    String[] words = line.split("\\.");
    wr = "";
    mean = "";
    if (words.length > 2) {
        wr = words[0] + words[1];
        mean = words[2];

    } else {
        wr = words[0];
        mean = words[1];
    }
}