How to match letters only using java regex, matches method?
[A-Za-z ]*
to match letters and spaces.
"[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+\\.?"));