C++ Subpattern Matching

后端 未结 3 613
遥遥无期
遥遥无期 2021-01-15 01:51

can anyone please show me an example about using regex (regex.h) in C/C++ to search and/or extracting subpattern in a regex.

in javascript, it will be something like

相关标签:
3条回答
  • 2021-01-15 02:12

    The only regular expressions readily available in C++ is boost::regex, and that is what has been adopted for the next standard. And the syntax is:

    boost::regex expr( "the string contains (\\d*) dots and (\\d*) chars" );
    boost::smatch match;
    if ( regex_match( text, match, expr ) ) {
        //  We have a match,
        std::string dots = match[1];
        std::string chars = match[2];
        //  ...
    }
    
    0 讨论(0)
  • 2021-01-15 02:14

    There is no regex.h in standard C or standard C++, so I'm assuming you mean the POSIX regular expression library. C example:

    char const *str = "the string contains 123 dots and 344 chars";
    char const *re_str = "the string contains ([0-9].*?) dots and ([0-9].*?) chars";
    regex_t compiled;
    regmatch_t *groups;
    
    regcomp(&compiled, re_str, REG_EXTENDED);
    
    ngroups = compiled.re_nsub + 1;
    groups = malloc(ngroups * sizeof(regmatch_t));
    regexec(&compiled, str, ngroups, groups, 0);
    
    for (size_t i = 0; i < ngroups; i++) {
        if (groups[i].rm_so == (size_t)(-1))
            break;
        else {
            size_t len = groups[i].rm_eo - groups[i].rm_so;
            char buf[len + 1];
            memcpy(buf, str + groups[i].rm_so, len);
            buf[len] = '\0';
            puts(buf);
        }
    }
    free(groups);
    

    (Add your own error checking. For more details, see this answer.)

    0 讨论(0)
  • 2021-01-15 02:18

    Neither C nor C++ has a "regex.h". The newest version of C++ (commonly called C++0x) will have regular expression support, but it will be Boost.Regex, more or less. So you may as well just ask, "How do I use Boost.Regex?"

    0 讨论(0)
提交回复
热议问题