Tony Stark Tony Stark - 1 month ago 7
Java Question

why an empty array gets printed out when trying to split a string using split(".")

I'm experimenting with String class's instance method split(). However, when I use

.
as split() method's argument and trying to print it out using
Arrays.toString(s2)
, only an empty array gets printed out.

Why is this happening?

String s1 = "hello.world";
String[] s2 = s1.split(".");
System.out.println(Arrays.toString(s2));

Answer

This " weird" behavior is because you are not scaping the dot in the regex... i.e you need to do s1.split("\\."); and not s1.split(".");

Example:

public static void main(String[] args) {
        String s1 = "hello.world";
        String[] s2 = s1.split("\\.");
        System.out.println(Arrays.toString(s2));
}

just for the learning process the dot in the regex belongs to the known metacharacters and every time you try to use regexwith them they must be scaped...

take a look at this tutorial for more info...

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".