Match letters regex java

If you are trying to match word contains letters upper case or lower case please use below regex:

package com.javahonk.patternmatch;

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

public class FindWordOnlyLetters {

    public static void main(String[] args) {

    //Find exact string
    String value = "brown";
    Pattern p = Pattern.compile("brown");
    Matcher m = p.matcher(value);
    boolean 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);

    }

}

 

Output:
find_exact_word_charecter

Leave a Reply

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