Thursday, May 17, 2007

Using a Non-Capturing Group in a Regular Expression

By default, a group captures text (see Capturing Text in a Group in a Regular Expression). In some cases, a group is needed but there is no need to capture the text. A non-capturing group should be used to improve performance. A non-capturing group starts with (?:.
    String inputStr = "abbabcd";
    String patternStr = "(a(?:b*))+(c*)";
    // (?:b*) is a non-capturing group
    
    // Compile and use regular expression
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.find();
    
    if (matchFound) {
        // Get all groups for this match
        for (int i=0; i<=matcher.groupCount(); i++) {
            String groupStr = matcher.group(i);
        }
        // group 0: abbabc
        // group 1: ab
        // group 2: c
    }

0 comments:

 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory