Java Program to Convert String to String Array Using Regular Expression
Last Updated :
02 Jun, 2022
Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java. util.regex package. This consists of 3 classes and 1 interface. Hence, in short, we can conclude, java’s regular expression is used to find, match, and extract data from character sequences.
Approach: We can convert String to String Array using the split method of the String class and Regular Expression.
- First, we split the string with the help of Regular Expression
- Now store this in an array.
- Print and display on the console
Methods:
- Using split() method only
- Using ‘?!^’ regular expression along with split() method
Method 1: Using split() method only
Example:
Java
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
String gfg = "Welcome, to, GFG" ;
String[] str = gfg.split( "," );
for (String s : str) {
System.out.println(s);
}
}
}
|
Method 2: Using ‘?!^’ regular expression along with split() method
Approach:
With the split method, we will use the ?!^ Regular Expression that split the string. And extract data of character sequence.
- ?! — It means a negative look ahead.
- ^ — It is the start of the string.
Example:
Java
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
String gfg = "Welcome, to, GFG" ;
String[] str = gfg.split( "(?!^)" );
System.out.println(Arrays.toString(str));
}
}
|
Output
[W, e, l, c, o, m, e, ,, , t, o, ,, , G, F, G]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...