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

20 java regex

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]");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出为False.我哪里错了?此外,我想检查一个单词是否只包含字母,并且可能或可能不以一个句点结束.这是什么样的正则表达式?

即"abc""abc." 有效但"abc .."无效.

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

use*_*own 43

"[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\\.?"));
Run Code Online (Sandbox Code Playgroud)

结合两种模式:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));
Run Code Online (Sandbox Code Playgroud)

而不是a-zA-Z,\ w通常更合适,因为它捕获äöüßø等外来字符:

System.out.println ("abc.".matches ("\\w+\\.?"));   
Run Code Online (Sandbox Code Playgroud)

  • 注意,'\ w`撷也下划线和数字,即`[A-ZA-Z_0-9]`如[图案]定义(https://docs.oracle.com/javase/7/docs/api/的java/UTIL /正则表达式/ Pattern.html) (2认同)

kga*_*ron 6

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