SCJP6 正则表达式问题 [英] SCJP6 regex issue

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

问题描述

我对以下示例有疑问:

import java.util.regex.*;
class Regex2 {
    public static void main(String[] args) {
        Pattern p = Pattern.compile(args[0]);
        Matcher m = p.matcher(args[1]);
        boolean b = false;
        while(b = m.find()) {
            System.out.print(m.start() + m.group());
        }
    }
}

还有命令行:

java Regex2 "d*" ab34ef

谁能给我解释一下,为什么结果是:01234456

Can someone explain to me, why the result is: 01234456

正则表达式模式是 d* - 表示第一个或多个,但在 args[1] 中有更多的位置,

regex pattern is d* - it means number one or more but there are more positions that in args[1],

谢谢

推荐答案

d* 匹配 0 个或多个数字.因此,它甚至会在每个字符之前和最后一个字符之后匹配空字符串.首先在索引 0 之前,然后在索引 1 之前,依此类推.

d* matches 0 or more digits. So, it will even match empty string before every character and after the last character. First before index 0, then before index 1, and so on.

因此,对于字符串 ab34ef,它匹配以下组:

So, for string ab34ef, it matches following groups:

Index    Group
  0        ""  (Before a)
  1        ""  (Before b)
  2        34  (Matches more than 0 digits this time)
  4        ""  (Before `e` at index 4)
  5        ""  (Before f)
  6        ""  (At the end, after f)

如果您使用 \d+,那么您将在 34 处只得到一个组.

If you use \d+, then you will get just a single group at 34.

这篇关于SCJP6 正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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