【问题标题】:Extracting submatches using boost regex in c++在 C++ 中使用 boost regex 提取子匹配
【发布时间】:2011-11-10 08:49:00
【问题描述】:

我正在尝试使用 boost 正则表达式从文本文件中提取子匹配项。目前我只返回第一个有效行和整行而不是有效的电子邮件地址。我尝试使用迭代器并使用子匹配,但我没有成功。这是当前代码:

if(Myfile.is_open()) {
    boost::regex pattern("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$");
    while(getline(Myfile, line)) {
            string::const_iterator start = line.begin();
            string::const_iterator end = line.end();
            boost::sregex_token_iterator i(start, end, pattern);
            boost::sregex_token_iterator j;
            while ( i != j) {
            cout << *i++ << endl;  

    } 
    Myfile.close(); 
}

【问题讨论】:

    标签: c++ regex boost


    【解决方案1】:

    使用boost::smatch

    boost::regex pattern("what(ever) ...");
    boost::smatch result;
    if (boost::regex_search(s, result, pattern)) {
        string submatch(result[1].first, result[1].second);
        // Do whatever ...
    }
    

    【讨论】:

    • 也许我的正则表达式是错误的,但这对我来说并没有产生正确的结果。
    【解决方案2】:
    const string pattern = "(abc)(def)";  
    const string target = "abcdef"; 
    
    boost::regex regexPattern(pattern, boost::regex::extended); 
    boost::smatch what; 
    
    bool isMatchFound = boost::regex_match(target, what, regexPattern); 
    if (isMatchFound) 
    { 
        for (unsigned int i=0; i < what.size(); i++) 
        { 
            cout << "WHAT " << i << " " << what[i] << endl; 
        } 
    } 
    

    输出如下

    WHAT 0 abcdef 
    WHAT 1 abc 
    WHAT 2 def 
    

    Boost 使用带括号的子匹配,第一个子匹配始终是完整匹配的字符串。 regex_match 必须将整行输入与模式匹配,如果您尝试匹配子字符串,请改用 regex_search。

    我上面使用的示例使用了 posix 扩展正则表达式语法,它是使用 boost::regex::extended 参数指定的。省略该参数会将语法更改为使用 perl 样式的正则表达式语法。其他正则表达式语法可用。

    【讨论】:

      【解决方案3】:

      这一行:

      string submatch(result[1].first, result[1].second);
      

      在 Visual c++ 中导致错误(我针对 2012 年进行了测试,但预计早期版本也会如此)

      请参阅https://groups.google.com/forum/?fromgroups#!topic/cpp-netlib/0Szv2WcgAtc 进行分析。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多