正则表达式无法匹配()模式与星号 [英] Regular Expression fails to matches() pattern with asterisk sign

查看:194
本文介绍了正则表达式无法匹配()模式与星号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

    String test = "Z";
    Pattern pt = Pattern.compile("[0-9]*");
    Matcher mc = pt.matcher(test);
    System.out.println(mc.find());
    System.out.println(mc.matches());

据我所知,它应该打印两个true。但是,匹配() print false。
星号表示零次或多次,为什么匹配()产生错误?

As far as I know, it should print two true. However, the matches() print false. The asterisk means zero or more times so why matches() produces false?

matches()尝试匹配整个字符串,这对我来说没问题,因为星号给了我零时间。

matches() tries to match the whole string and it is okay for me since asterisk gives me zero time.

所以为什么匹配失败?

推荐答案

模式 [0-9] * 说匹配0-9的0次或更多次。 如果它看到一个数字,它会将其添加到匹配中。如果它没有看到数字,它仍然会在匹配中添加一个0长度的字符串。这并不意味着匹配任何具有0或更多位数的字符串(因为每个字符串都有0或更多位数,这使得这没有意义)所以在你的字符串 Z 中,有两个零长度匹配:一个在字符串的开头,另一个在字符串的末尾,两者都有0位数。

The pattern [0-9]* says "matches 0 or more times of 0-9". If it sees a digit it will add that to the match. If it doesn't see a digit it still adds a 0 length string to the match. It does not mean match any string with 0 or more digits (because every string has 0 or more digits, which makes this pointless) So in your string Z, there are two zero-length matches: one at the start of the string and one at the end of the string, both of which has 0 digits.

这意味着 find 将返回true两次,匹配将返回false,因为整个字符串不匹配(记住有匹配!)。

This means that find will return true twice and matches will return false because the whole string is not a match (remember there are wo matches!).

这篇关于正则表达式无法匹配()模式与星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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