如何只使用java正则表达式匹配字母,匹配方法? [英] How to match letters only using java regex, matches method?
问题描述
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]");
}
}
输出为False。我哪里错了?此外,我想检查一个单词是否只包含字母,并且可能或可能不以一个句点结束。那是什么样的正则表达式?
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?
即abcabc。有效但abc ..无效。
i.e "abc" "abc." is valid but "abc.." is not valid.
我可以用 indexOf()
方法解决它,但我想知道是否可以使用一个正则表达式。
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]
只匹配一个字符。要匹配多个字符,请使用[a-zA-Z] +
。
"[a-zA-Z]"
matches only one character. To match multiple characters, use "[a-zA-Z]+"
.
由于点是a任何角色的小丑,你必须掩饰它:abc \。
要使点可选,你需要一个问号:
abc \。?
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\.?"
如果在代码中将Pattern写为文字常量,则必须屏蔽反斜杠:
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\\.?"));
结合两种模式:
System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));
而不是a-zA-Z,\ w通常更合适,因为它捕获外来字符喜欢äöüßø等等:
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+\\.?"));
这篇关于如何只使用java正则表达式匹配字母,匹配方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!