简体   繁体   中英

How to control the iteration step in Java regex?

The topic is confusing, however for example,

final String pattern = "(abc)";

final String content = "dabcef";

Matcher m = Pattern.compile(pattern).matcher(content);

The m.find() will surely return true.

I want to know if it's possible to process chars only once, meaning

"dab" -> not found, "cef" -> not found, over.

Thanks!

EDIT:

Actually I want to find all matches instead of only check if matches or not. For example,

abc abc def abc dab cef (actually without spaces)

will be matched by ^(.{3})*?(abc), however only once. And I expect 3 matches.

Thanks!

怎么样:

final String pattern = "^(.{3})*(abc)";

I found the solution by moving start index. Thank @Oil for the suggestion!

public static void main(String[] args) {
    final String pattern1 = "^(.{3})*?(abc)";

    final String content1 = "efabcabcdabcefaabcdfabce"; // two matches

    final String content2 = "abcabcdabcefabc"; // three matches

    Matcher mStart = Pattern.compile(pattern1).matcher(content1);

    while (mStart.find()) {
        System.out.println(mStart.group(mStart.groupCount()));
        System.out.println(mStart.start() + ", " + mStart.end());

        mStart = mStart.region(mStart.end(), mStart.regionEnd());
    }

    //-----------------------------
    System.out.println("------------------------");

    mStart = Pattern.compile(pattern1).matcher(content2);

    while (mStart.find()) {
        System.out.println(mStart.group(mStart.groupCount()));
        System.out.println(mStart.start() + ", " + mStart.end());

        mStart = mStart.region(mStart.end(), mStart.regionEnd());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM