How to use Java String.split method to split a string by dot?

In java, string.split(".") does not work for splitting a string with dot (e.g., www.xyzws.com) and will give you an array with zero element.

The Sting split(String regex) method wants a regular expression as its parameter. It splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

In regular expression, the "." is a metacharacter with special meaning which matches any single character except a newline. You got an array with zero element because "." mataches any charachers in your string.

A preceding backslash ("\") turns a metachacter into a literal character. Because this is also the Java escape character in strings, you need to use "\\" to present the backslash character. To split a string with a literal '.' character in Java, you must use split("\\."). For example,

 String domain = “www.xyzw.com”;
 String[] strArray = domain.split(“\\.”);
 for (String str : strArray) {


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |