Pattern Matching In Java Example
Chapter:
Regular Expression
Last Updated:
09-07-2016 05:19:07 UTC
Program:
/* ............... START ............... */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaPatterMatching {
public static void main(String args[]) {
Pattern pat;
Matcher mat;
boolean found;
pat = Pattern.compile("Java");
mat = pat.matcher("Java");
found = mat.matches(); // check for a match
System.out.println("Testing Java against Java.");
if (found)
System.out.println("Matches");
else
System.out.println("No Match");
System.out.println("Testing Java against Java 8.");
mat = pat.matcher("Java 8"); // create a new matcher
found = mat.matches(); // check for a match
if (found)
System.out.println("Matches");
else
System.out.println("No Match");
}
}
/* ............... END ............... */
Output
Testing Java against Java.
Matches
Testing Java against Java 8.
No Match
Notes:
-
Java provides the java.util.regex package for pattern matching with regular expressions.
- A regular expression, also known as a regex or regexp, is a string whose pattern (template) describes a set of strings.
Tags
Java Pattern Matching, Regular Expression