Matching a String Against a Pattern - Java Regular Expressions

Java examples for Regular Expressions:Match

Description

Matching a String Against a Pattern

Demo Code

public class Main {
  public static void main(String[] args) {
    // Prepare a regular expression to represent a pattern
    String regex = ".@.";
                /*from   w w  w .j a v  a 2  s. c  o m*/
                // Try matching many strings against the regular expression
    Main.matchIt("a@k", regex);
    Main.matchIt("webmaster@mypkg.com", regex);
    Main.matchIt("r@j", regex);
    Main.matchIt("a%N", regex);
    Main.matchIt(".@.", regex);
  }

  public static void matchIt(String str, String regex) {
    // Test for pattern match
    if (str.matches(regex)) {
      System.out.println(str + " matches the regex " + regex);
    }
    else {
      System.out.println(str + " does not match the regex " + regex);
    }  
  }
}

Result


Related Tutorials