且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式在 String.matches() 中不起作用

更新时间:2023-02-26 11:56:26

欢迎使用 Java 的错误命名 .matches() 方法......它尝试并匹配所有输入.不幸的是,其他语言也纷纷效仿:(

Welcome to Java's misnamed .matches() method... It tries and matches ALL the input. Unfortunately, other languages have followed suit :(

如果您想查看正则表达式是否与输入文本匹配,请使用 PatternMatcher.find() 方法匹配器:

If you want to see if the regex matches an input text, use a Pattern, a Matcher and the .find() method of the matcher:

Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(inputstring);
if (m.find())
    // match

如果你确实想看输入是否只有小写字母,你可以使用.matches(),但你需要匹配一个或多个字符:附加一个+ 到您的字符类,如 [az]+ .或者使用 ^[a-z]+$.find().

If what you want is indeed to see if an input only has lowercase letters, you can use .matches(), but you need to match one or more characters: append a + to your character class, as in [a-z]+. Or use ^[a-z]+$ and .find().