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)
| 归档时间: |
|
| 查看次数: |
115073 次 |
| 最近记录: |