Pattern Matcher java

Pattern Matcher java

Java API has provided final class Pattern which we can use to match regular expression. Below is sample java program shows how to use it:

package com.javahonk.patternmatch;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatcherTest {

    public static void main(String[] args) {

    String value = "The quick brown fox jumps over the lazy dog";
    //Find exact word match "quick"
    Pattern p = Pattern.compile(".*\\bquick\\b.*");
    Matcher m = p.matcher(value);
    boolean b = m.matches();
    System.out.println("Find exact word match: "+b);

    //Find exact word match ignore case ("quiCK") or any small or cap letter
    value = "The quiCK brown fox jumps over the lazy dog";
    p = Pattern.compile(".*\\b[qQ][uU][iI][cC][kK]\\b.*");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find exact word match "
            + "ignore case: "+b);

    //Find exact string
    value = "brown";
    p = Pattern.compile("brown");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find exact string: "+b);

    //Find exact string ignore case first letter
    value = "brown";
    p = Pattern.compile("[bB]rown");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find exact string "
            + "ignore case first letter: "+b);

    //Find string with character
    value = "brown";
    p = Pattern.compile("[A-Za-z]+");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find string with "
            + "character: "+b);

    //Find string with character or number
    value = "brown196";
    p = Pattern.compile("[A-Za-z0-9]+");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find string with "
            + "character or number: "+b);

    //Find string with character and .
    value = "brown.";
    p = Pattern.compile("brown\\.?");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find string with "
            + "character and .: "+b);

    //Find any character except d,e
    value = "brown";
    p = Pattern.compile("[^de]+");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find any character "
            + "except d,e: "+b);

    //Find a through z or A through Z
    value = "brown";
    p = Pattern.compile("[A-Za-z0-9]+");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find a through z "
            + "or A through Z: "+b);

    //Find a through c or s through u
    value = "abcstu";
    p = Pattern.compile("[abc[stu]]+");
    m = p.matcher(value);
    b = m.matches();
    System.out.println("Find a through c"
            + " or s through u: "+b);

    }

}

 

Output:

Pattern Matcher java

 

Note: For details tutorial on regular expression please visit Oracle site

Leave a Reply

Your email address will not be published. Required fields are marked *