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.
"[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+\\.?"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With