Wednesday, April 12, 2023

How to Split String in Java using Regular Expression

String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits the string based on delimiter provided, and return a String array, which contains individual Strings. Actually, split() method takes a regular expression, which in simplest case can be a single word. split() is also overloaded method in java.lang.String class and its overloaded version take a limit parameter which is used to control how many times the pattern will be applied during the splitting process. if this limit is positive n, then the pattern will be applied at most n-1 times, if it's negative or zero then split operation is applied any number of times.

 For example, if we split String "First,Second,Third" on comma and provide limit as 2 then pattern will run one time, and split() will return String array with 2 Strings, "First" and "Second,Third". 

Since this method accepts a Java regular expression, it throws PatternSyntaxException, if the syntax of the regular expression is invalid.


String Split Example in Java

String Split Example with regular expression in JavaLet's see a couple of String Split example in Java. In the first example, we will split a colon separated String on colon as a delimiter, and in the second example, we will split comma separated String. 



In the third example, we will split String using the regular expression, which actually splits a String on space as delimiter. \\s is a regular expression to find spaces. \s is actually used to match any white space character including newline, tab, form feed e.g. \t, \n, \r, and \f. \\ is to escape backward slash which is an escape character in Java. 


If you are familiar with Java Regular Expression, then split(regex) method is similar to Pattern.compile(regex).split().

package test;

/**
 * Java program to split String in Java using delimiter.
 * This String Split example shows how to split String in Java using comma,
 * colon and space as delimiter.
 * Splitting String by space uses regular expression \\s to split String.
 *
 * @author http://java67.blogspot.com
 */
public class StringSplitExample {
 
    public static void main(String args[]) {

      //Splitting colon separated String in Java
      String colon = "Java:J2EE:JavaFX:JavaME";
     
      String[] strings = colon.split(":");
     
      System.out.println("Original Colon Separated String : " + colon);
      System.out.println("String splitted using Split() method 
                   of java.lang.String in Java");
     
      for(String str : strings){
          System.out.println(str);
      }
     
      //Splitting comma separated String in Java
      String comma = "Android,Windows 8,iOS,Symbian";
      String[] strs = comma.split(",");
      System.out.println("Original comma separated String : " + comma);
      System.out.println("Splitting String using split() method in Java");
    
      for(String str: strs){
          System.out.println(str);
      }
     
      //Splitting String on space as delimiter in Java
      String space = "String Split Example in Java";
      String[] words = space.split("\\s");
      System.out.println("Space separated String before split : " + space);
      System.out.println("Space separated String after split");
     
      for(String word: words){
          System.out.println(word);
      }
    
    } 
   
}
Output:
Original Colon Separated String : Java:J2EE:JavaFX:JavaME
String splitted using Split() method of java.lang.String in Java
Java
J2EE
JavaFX
JavaME
Original comma separated String : Android,Windows 8,iOS,Symbian
Splitting String using split() method in Java
Android
Windows 8
iOS
Symbian
Space separated String before split : String Split Example in Java
Space separated String after split
String
Split
Example
in 
Java

That's it on How to split String in Java using delimiter and regular expression. The split(regex) method is very powerful, and all its power comes from the regular expression. Though it's not required to know regular expressions to split String in Java, but if you know regex, it is only going to help you.


Related Java String tutorials from Java67 Blog

10 comments:

  1. Remember, when you split String, it always create a new String object, because String is Immutable in Java.

    ReplyDelete
  2. how to split a word hithis into two words in java like hi this.

    ReplyDelete
  3. How to split two string having any operator between them
    "23+56","45-89","5656*4554"

    ReplyDelete
  4. Using regular expressions.
    str.split("[-+*/]")

    ReplyDelete
  5. what is meanig of this regular expression used in String split method?
    (?<=\\G.{25000})

    ReplyDelete
    Replies
    1. The regex (?<=\\G.{25000}) matches an empty string that has the last match (\G) followed by 25000 characters (.{25000}) before it ((?<= )).

      i.e,
      In General, let me take simple regex which is (?<=\\G.{3}) instead of something which is being specified just to make it understand.

      String bitstream = "001010100010010101001010101001010101010010";
      String[] str = bitstream.split("(?<=\\G.{5})");
      Thus,
      str = {"00101", "01000", "10010", "10100", "10101", "01001", "01010", "10100", "10"}

      Delete
  6. what is this mean ~ /(.*)\.[0-9]+$/

    ReplyDelete
  7. Replies
    1. In C#,
      string exp = "1-1,3];4";
      char[] ch = {'-', ',', ']', ';'};
      string[] str = exp.Split(ch);
      Thus,
      str = {"1", "1", "3", "", "4"}

      if wants to remove null values then,
      stirng[] str = exp.Split(ch, StringSplitOptions.RemoveEmptyEntries);
      Thus,
      str = {"1", "1", "3", "4"}

      Delete

Feel free to comment, ask questions if you have any doubt.