如何仅使用java正则表达式匹配字母,匹配方法?

2022-09-01 18:22:54
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。我哪里出错了?另外,我想检查一个单词是否只包含字母,并且可能以单个句点结尾,也可能不以单个句点结尾。正则表达式是什么?

即“abc”“abc.”是有效的,但“abc..”是无效的。

我可以使用方法来解决它,但我想知道是否可以使用单个正则表达式。indexOf()


答案 1

"[a-zA-Z]"仅匹配一个字符。要匹配多个字符,请使用 。"[a-zA-Z]+"

由于点对于任何角色来说都是小丑,因此您必须掩盖它:要使点可选,您需要一个问号:"abc\.""abc\.?"

如果在代码中将 Pattern 编写为文本常量,则必须屏蔽反斜杠:

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 通常更合适,因为它捕获了 äöüßø 等外来字符:

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

答案 2

[A-Za-z ]*以匹配字母和空格。