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
121 views
in Technique[技术] by (71.8m points)

java - How to iterate over regex expression

Let's say I have the following String:

name1=gil;name2=orit;

I want to find all matches of name=value and make sure that the whole string matches the pattern.

So I did the following:

  1. Ensure that the whole pattern matches what I want.

    Pattern p = Pattern.compile("^((\w+)=(\w+);)*$");
    Matcher m = p.matcher(line);
    if (!m.matches()) {
        return false;
    }
    
  2. Iterate over the pattern name=value

    Pattern p = Pattern.compile("(\w+)=(\w+);");
    Matcher m = p.matcher(line);
    while (m.find()) {
        map.put(m.group(1), m.group(2));
    }
    

Is there some way to do this with one regex?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can validate and iterate over matches with one regex by:

  • Ensuring there are no unmatched characters between matches (e.g. name1=x;;name2=y;) by putting a G at the start of our regex, which mean "the end of the previous match".

  • Checking whether we've reached the end of the string on our last match by comparing the length of our string to Matcher.end(), which returns the offset after the last character matched.

Something like:

String line = "name1=gil;name2=orit;";
Pattern p = Pattern.compile("\G(\w+)=(\w+);");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
   System.out.println(m.group(1));
   System.out.println(m.group(2));
   lastMatchPos = m.end();
}
if (lastMatchPos != line.length())
   System.out.println("Invalid string!");

Live demo.


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

...