Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

java - SCJP6 regex issue

I have issue with following example:

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());
        }
    }
}

And the command line:

java Regex2 "d*" ab34ef

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

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

thanks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...