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) {
System.out.println(str);
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?