Tony Stark Tony Stark - 1 year ago 61
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
, only an empty array gets printed out.

Why is this happening?

String s1 = "";
String[] s2 = s1.split(".");

Answer Source

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(".");


public static void main(String[] args) {
        String s1 = "";
        String[] s2 = s1.split("\\.");

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".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download