【问题标题】:tr1::regex regex_search problemtr1::regex regex_search 问题
【发布时间】:2010-08-29 04:14:13
【问题描述】:

我正在使用 tr1::regex 尝试从字符串中提取一些匹配项。一个示例字符串可以是

asdf werq "one two three" asdf

我想摆脱这种情况:

asdf  
werq  
one two three  
asdf  

引号中的内容组合在一起,所以我尝试使用正则表达式\"(.+?)\"|([^\\s]+)。我使用的代码是:

cmatch res;
regex reg("\"(.+?)\"|([^\\s]+)", regex_constants::icase);
regex_search("asdf werq \"one two three\" asdf", res, reg);

cout << res.size() << endl;
for (unsigned int i = 0; i < res.size(); ++k) {
    cout << res[i] << endl;
}

但是输出

3
asdf

asdf

我做错了什么?

【问题讨论】:

    标签: regex search matching tr1


    【解决方案1】:

    您的正则表达式引擎似乎不支持后向断言。为避免使用lookbehinds,您可以尝试以下方法:

    "([^"]*)"|(\S+)
    

    或引用:

    "\"([^\"]*)\"|(\\S+)"
    

    这个正则表达式可以工作,但每个匹配都会有两个捕获,其中一个是空的(第一个 - 如果是未引用的单词,或者第二个 - 如果是带引号的字符串)。

    为了能够使用它,您需要遍历所有匹配项,并为每个匹配项使用非空捕获。

    我对 TR1 了解的不够多,所以我不确切知道如何迭代所有匹配项。但如果我没记错的话,res.size() 将始终等于 3。

    例如,对于字符串asdf "one two three" werq,第一个匹配项将是:

    res[0] = "asdf"              // the entire match
    res[1] = ""                  // the first capture
    res[2] = "asdf"              // the second capture
    

    第二场比赛将是:

    res[0] = "\"one two three\"" // the entire match including leading/trailing quotes
    res[1] = "one two three"     // the first capture
    res[2] = ""                  // the second capture
    

    第三场比赛将是:

    res[0] = "werq"              // the entire match
    res[1] = ""                  // the first capture
    res[2] = "werq"              // the second capture
    

    HTH。

    【讨论】:

    • 如果我使用迭代器,我将如何获得您所说的匹配项?您使用 for (std::tr1::sregex_token_iterator i(str.begin(), str.end(), reg); i != end; ++i) { cout
    • 以下内容如何:for (std::tr1::sregex_token_iterator i(str.begin(), str.end(), reg); i != end; ++i) { cout &lt;&lt; ((*i)[1] || (*i)[2]); }?我无法检查它是否编译,更不用说运行了,但想法是 *i 是一个具有索引运算符的对象,它应该为您提供捕获。
    【解决方案2】:

    您可能想尝试以下正则表达式:

    (?<=")[^"]*(?=")|[^"\s]\S*
    

    引用的时候当然需要转义:

    "(?<=\")[^\"]*(?=\")|[^\"\\s]\\S*"
    

    顺便说一句,您使用的代码可能只匹配目标字符串中的第一个单词,因为它不使用 match_any。您在结果中获得的 3 个项目可能是 (1) 整个匹配项,(2) 第一次捕获 - 为空,以及 (3) 第二次捕获,这是匹配的来源。

    【讨论】:

    • 实际上,当我使用该正则表达式时,当我运行程序时,它会输出到控制台:“此应用程序已请求运行时以不寻常的方式终止它。请联系...”等等等等等等,它崩溃了。
    • 我没有可以检查这个的工作环境,但我已经用 Java 和 C# 测试了正则表达式,它也没有崩溃。请使用 syntax_option_type=extended 以确保它遵循扩展正则表达式的标准语法。 (顺便说一句,我对正则表达式的第一部分做了一个小修复,以防止它在引用的单词末尾捕获空格。)
    • 你被邀请在这里玩正则表达式:myregextester.com/?r=a9e366fd
    • 我把它改成了正则表达式 reg("(?
    • 奇怪的错误:无论我使用什么正则表达式, regex_constants::syntax_option_type::extended 总是让它​​崩溃。如果我将其取出并从您的正则表达式中删除 (?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2019-03-31
    • 2016-09-26
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多