Java-Regular Expressions with String Class

Regular Expressions with String Class

If all you want to do with a regular expression is check to see whether a string matches a pattern, you can use the matches( ) method of the String class. This method accepts a regular expression as a parameter and returns a boolean that indicates whether or not the string matches the pattern.

Program

 

You can also use the split method to split a string into an array of String objects based on delimiters that match a regular expression. For example, in the following program, a string is split into three words marked by spaces.

Program

Program Source

public class Javaapp {
  
    public static void main(String[] args) {
        
        String str = new String("Java Programming Tutorial");
        boolean b = str.matches(".*Programming.*");
        System.out.println(b);
    }
}

Program Source

public class Javaapp {
  
    public static void main(String[] args) {
        
        String str = new String("Java Programming  Tutorial");
        String strs[] = str.split("\\s+");
        for(String st : strs)
            System.out.println(st);
        
    }
}

Leave a Comment