Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match letters only using java regex, matches method?

Tags:

java

regex

import java.util.regex.Pattern;

class HowEasy {
    public boolean matches(String regex) {
        System.out.println(Pattern.matches(regex, "abcABC   "));
        return Pattern.matches(regex, "abcABC");
    }

    public static void main(String[] args) {
        HowEasy words = new HowEasy();
        words.matches("[a-zA-Z]");
    }
}

The output is False. Where am I going wrong? Also I want to check if a word contains only letters and may or maynot end with a single period. What is the regex for that?

i.e "abc" "abc." is valid but "abc.." is not valid.

I can use indexOf() method to solve it, but I want to know if it is possible to use a single regex.


1 Answers

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   
like image 97
user unknown Avatar answered Sep 08 '25 06:09

user unknown