正则表达式在String.matches()中不起作用 [英] Regex doesn't work in String.matches()

查看:296
本文介绍了正则表达式在String.matches()中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码

String[] words = {"{apf","hum_","dkoe","12f"};
for(String s:words)
{
    if(s.matches("[a-z]"))
    {
        System.out.println(s);
    }
}

打算打印

dkoe

但它什么都不打印!!

but it prints nothing!!

推荐答案

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

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

如果你想查看正则表达式是否与输入文本匹配,请使用模式,一个匹配器和匹配器的 .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] + 。或者使用 ^ [az] + $ .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().

这篇关于正则表达式在String.matches()中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆