1

I was working on String and tried with split() for . like:-

String s = "Hi.Hello";
System.out.println(Arrays.toString(s.split(".")));

The above code outputs [] empty array. But if I escape . like :-

String s = "Hi.Hello";
System.out.println(Arrays.toString(s.split("\\.")));

Its giving correct output as [Hi, Hello].

So I Want To Know:-

Why do i need to escape . but . it is normally not considered a escape character in String as we can use . directly.

Community
  • 1
  • 1
AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23

3 Answers3

14

The String.split( String ) method takes a regular expression as argument. In a regular expression "." means "any character", so you have to escape it (by adding "\\"), if you actually want to split by "." and not by "any character".

See the api documentation of Pattern for a starter on the regular expressions.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
4

You cannot split it with just . because split()

Splits this string around matches of the given regular expression.

In regex . means 'match any character', so you have to escape it with \\ instead of \ because you also have to escape the \ character!

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
Roberto Anić Banić
  • 1,411
  • 10
  • 21
1

Small addition to previous answers (which are correct).

It's often better to use StringUtils.split from Apache Commons Lang (javadoc). It takes plain string (instead of regex) as an argument. Also, its behaviour more intuitive:

StringUtils.split("a..b.c", ".") = ["a", "b", "c"]

vs

"a..b.c".split("\\.") = ["a", "", "b", "c"]
Ernest Sadykov
  • 831
  • 8
  • 28