简体   繁体   English

正则表达式在C ++中不起作用

[英]regular expression is not working in c++

I am trying to match a regular expression in c++ using regexec . 我正在尝试使用regexec匹配C ++中的正则表达式。

This is my pattern which i tried was working fine in java 这是我尝试在Java中正常工作的模式

(^.*([0-9]{6}).*([0-9]{9}).*([0-9]{6,7}).*([0-9]{2,3}).*)

I tried this, but getting wrong output 我尝试了这个,但是输出错误

(.*)[[:digit:]{6}](.*)[[:digit:]]{9}(.*)[[:digit:]]{6,7}(.*)[[:digit:]]{2,3}(.*)

Following is my c++ code : 以下是我的C ++代码:

static int compile_regex (regex_t * r, const char * regex_text) {
    int status = regcomp (r, regex_text, REG_EXTENDED|REG_NEWLINE);
    if (status != 0) {
        char error_message[MAX_ERROR_MSG];
        regerror (status, r, error_message, MAX_ERROR_MSG);
        printf ("Regex error compiling '%s': %s\n",
                 regex_text, error_message);
        return 1;
    }
    return 0;
}
static int match_regex (regex_t * r, char * to_match) {
    char * p = to_match;
    int n_matches = 10;
    regmatch_t m[n_matches];
    int i = 0;
    int nomatch = regexec (r, p, n_matches, m, 0);
    return nomatch;
}
int match ( char * find_text ,string regex_txt) {

    char regex_text[regex_txt.size()+1];
    strcpy(regex_text , regex_txt.c_str());
    regex_t r;
    int ret ;
    compile_regex (& r, regex_text);
    ret = match_regex (& r, find_text);
    return ret;
}

There's nothing wrong with POSIX regex, however if you wanted to do this in portable c++11, something like the following will work.. POSIX正则表达式没有问题,但是,如果您想在可移植的c ++ 11中执行此操作,则类似以下内容的方法将起作用。

#include <iostream>
#include <regex>

using namespace std;

int main(void) {
    auto str = string("@000172@ 000002000[ 000001@ 13 8");
    auto rx = regex("(^.*([0-9]{6}).*([0-9]{9}).*([0-9]{6,7}).*([0-9]{2,3}).*)");
    auto it = sregex_iterator(str.begin(), str.end(), rx);
    auto ie = sregex_iterator();

    cout << "Found " << distance(it, ie) << " matches\n";
    // print submatches
    for (auto i = it; i != ie; ++i) {
        for(auto s : *i) {
            cout << s << endl;
        }
    }
}

And https://regex101.com/ confirms, that the code is doing the right thing - ie the output looks like this: 然后https://regex101.com/确认代码正在做正确的事情-即输出看起来像这样:

Found 1 matches
@000172@ 000002000[ 000001@ 13 8
@000172@ 000002000[ 000001@ 13 8
000172
000002000
000001
13

不要使用与数字也匹配的点,而使用与NON数字匹配的\\D

(^\D*([0-9]{6})\D*([0-9]{9})\D*([0-9]{6,7})\D*([0-9]{2,3})\D*)

Check if your compiler is actually supports regex. 检查您的编译器是否实际上支持正则表达式。 I had the situation with GCC when it looks like regex are supported (all headers are exists, compilation is OK and so on), but actual result of matching is wrong. 当看起来正则表达式受支持时,我遇到了GCC(所有标头都存在,编译可以,依此类推),但是匹配的实际结果是错误的。 Updating GCC to the newer version solved the problem. 将GCC更新到较新版本可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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