java split using regex code example

Example 1: how to split a string in java

// Java program to demonstrate working of split(regex, 
// limit) with small limit. 
public class GFG { 
    public static void main(String args[]) 
    { 
        String str = "geekss@for@geekss"; 
        String[] arrOfStr = str.split("@", 2); 
  
        for (String a : arrOfStr) 
            System.out.println(a); 
    } 
}

Example 2: splitting using regex java

Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
Matcher m = p.matcher("810LN15");
List<String> tokens = new LinkedList<String>();
while(m.find())
{
  String token = m.group( 1 ); //group 0 is always the entire match   
  tokens.add(token);
}
//now iterate through 'tokens' and check whether you have a number or text

Tags:

Java Example