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-w3wiki" ; // 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 w3wiki
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.
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-w3wiki”
String regex = “-”Output: “hello from w3wiki”
Contact Us