Open In App

How to Split Strings Using Regular Expressions in Java?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Split a String while passing a regular expression (Regex) in the argument and a single String will split based on (Regex), as a result, we can store the string on the Array of strings. In this article, we will learn how to split the string based on the given regular expression.

Example of Split String Using Regular Expression

Input: String s1 = “hello-from-GeeksforGeeks”
String regex = “-”

Output: “hello from GeeksforGeeks”

Java Program to Split the String based on the Regular Expression

First, we apply a String.split() on the given String and pass the given regex in the argument. It will return an Array of strings and we store it in the Array then we print the Array.

Syntax

str.split(regular_expression)

Below is the implementation of the topic:

Java




// java program to split a string.
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // give String
        String s1 = "hello-from-GeeksforGeeks";
  
        // given regex
        String regex = "-";
  
        // apply split() method on the given string and pass
        // regex in the argument.
  
        String[] split
            = s1.split(regex); // return an array of strings
  
        // printing output
        for (String s : split) {
            System.out.print(s + " ");
        }
    }
}


Output

hello from GeeksforGeeks 

Explaination of the above Program:

  1. Pass any kind of Regex it would be a single character or String to the split() method that will return the string array with replacing the elements.
  2. But if you try to split String with some special characters like * or / . which are predefined characters in regular expression.
  3. So it will not work so you need to pass regex in this form [//*]
  4. Here you need to use backslash(//) and the square bracket represents the specific character.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads