Find exact word regex java

Find exact word regex java

If you are trying to find regular expression which should match exact word from given input string please have below java demo program:

package com.javahonk.patternmatch;

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

public class PatternMatcher {

    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 mix of small and caps
    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: "+b);

    }

}

 

Output:

Find exact word regex java

Leave a Reply

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