我有以下Java代码
Pattern pattern = Pattern.compile("[a-zA-Z]+", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("1A");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
结果表明 1A 与正则表达式 "[a-zA-Z]+".
匹配我只需要接受以字母开头的单词。
我在问题中也做了同样的事情。
matcher.find()
查找输入中内的匹配项;在你的情况下它匹配 A
。
你想要
"1A".matches("[a-zA-Z]+")
必须匹配整个字符串才能返回
true
。
给定的正则表达式 [a-zA-Z]+ 匹配字符,无论其在字符串中的位置如何。这里 1A 也是一个匹配。
如果您想匹配以字母开头的单词,请在正则表达式的开头使用“^”。 “^”是标识字符串的开头。
要匹配零个或多个字母,您可以使用 [a-zA-Z]*,您的最终正则表达式如下所示。
exp - “^[a-zA-Z][a-zA-Z]*”