How to Split on String in Java with Regular Expressions by Dot.


There are various ways in which we can split a String in Java, but the most efficient way is making use of regular expressions.

If you have a String that you want to split on dot (.), then you can write you code as follows,

package org.code2care.example;

public class JavaSplitOnDotStringExample {

    public static void main(String[] args) {

        String sentence = "This is sentence one. This is sentence two";
        String[] splittedStringArray = sentence.split("\\.\\s");
        for (String string : splittedStringArray) {
            System.out.println(string);
        }

    }
}
Output:

This is sentence one
This is sentence two

We have made use of the split() function from the java.lang.String class

public String[] split(String regex)

Splits this string around matches of the given regular expression.


Let's see another example with Pattern and Matcher classes from java.util.regex.

package org.code2care.example;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaSplitOnDotStringExample2 {

    public static void main(String[] args) {
        String sentence = "1.2.3.4.5.6.7.8";
        Pattern pattern = Pattern.compile("(\\d+)");
        Matcher matcher = pattern.matcher(sentence);

        //Print them out
        while (matcher.find()) {
            String splittedString = matcher.group(1);
            System.out.print(splittedString+"\t");
        }
    }
}
Output:

1 2 3 4 5 6 7 8

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap