How to Split Strings Using Regular Expressions in Java?
Last Updated :
31 Jan, 2024
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
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = "hello-from-GeeksforGeeks" ;
String regex = "-" ;
String[] split
= s1.split(regex);
for (String s : split) {
System.out.print(s + " " );
}
}
}
|
Output
hello from GeeksforGeeks
Explaination of the above Program:
- 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.
- But if you try to split String with some special characters like * or / . which are predefined characters in regular expression.
- So it will not work so you need to pass regex in this form [//*]
- Here you need to use backslash(//) and the square bracket represents the specific character.
Share your thoughts in the comments
Please Login to comment...