How to split the string by dot in Java?

Contents

Dot(.) character in Regular Expression

Dot(.) is a special character in regular expression which is used to match any character. How do we escape dot in regex? Double backslash (\\) is used to escape these kind of special characters in regex. Hence we need to use \\. to split the string based on dot character.

Example 1: Dot(.) without double backslash in regex

Input String   : revisitclass
Regex to split : v.s

Here v.s means three character of string which starts with v followed by any character, then ending with s ( v + any character + s). It split the input string into two separate string as below (one before vis and the other one after vis)

  • re
  • itclass

Example 2: Java split string by dot with double backslash

Lets write the simple java program to split the string by dot. Here we are going to use double backslash(\\) along with dot that will escape the dot character.

Input String : www.revisitclass.com
Output Strings :
www
revisitclass
com

public class StringSplit {
    public static void main(String[] args) {
        //Input string
        String name = "www.revisitclass.com";
        //Mentioned dot with double backslash in regex
        String splitStr[] = name.split("\\.");
        //Print each string from the array
        for (String eachStr : splitStr){
            System.out.println(eachStr);
        }
    }
}

Output

www
revisitclass
com

Recommended Articles