Horje
How to Split Strings Using Regular Expressions in Java?

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.



Reffered: https://www.geeksforgeeks.org


Java Programs

Related
Convert a String to a ByteBuffer in Java Convert a String to a ByteBuffer in Java
How to Merge Two LinkedHashMaps in Java? How to Merge Two LinkedHashMaps in Java?
Binary to Decimal Conversion in Java Binary to Decimal Conversion in Java
Java Apache PDFBox - Programming Examples with Output Java Apache PDFBox - Programming Examples with Output
How to Extract Domain Name From Email Address using Java? How to Extract Domain Name From Email Address using Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14