C++11中regex_search查询

xtfmy6hx  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(113)

我正在探索C++11中的正则表达式库。我对'regex_search()'函数的行为有点困惑,我想澄清一下。下面是我的示例程序,它返回下面的输出

匹配模式的字符串:

test 1 2 3 4 5 abc def abc

我的问题是,为什么它不匹配模式test 1 2 3 4 5 abc,而只匹配test 1 2 3 4 5 abc def abc?对于给定的正则表达式,它是否也不匹配第一个(即test 1 2 3 4 5 abc)?有人能帮我理解吗?

#include <iostream> 
#include <regex> 
#include <string> 
using namespace std; 
   
int main()
{
    std::string inputStr = "test 1 2 3 4 5 abc def abc";
    std::string regexPattern = "test 1.*abc";
    
    regex regexp(regexPattern, std::regex::grep);
    smatch m; 
    
    while(std::regex_search(inputStr, m, regexp, std::regex_constants::match_default))
    {
        std::cout<<"String that matches the pattern: "<< m.str() << std::endl;
        inputStr = m.suffix();
    }
    
    return 0;
}
0lvr5msh

0lvr5msh1#

我能够使regex_search()匹配第一次出现的模式(即test 1 2 3 4 5 abc而不是test 1 2 3 4 5 abc def abc),通过搜索'lazy'而不是默认的'greedy' [感谢@Botje对'greedy matching'的评论,这给了我一些提示]。下面是对问题中发布的原始代码所做的更改(在更改的地方添加了注解)。

#include <regex> 
#include <string> 
using namespace std; 
   
int main()
{
    std::string inputStr = "test 1 2 3 4 5 abc def abc";
    std::string regexPattern = "test 1.*?abc"; // Added lazy quantifier '?' after the '.*' to make the search lazy instead of greedy
    
    regex regexp(regexPattern); // removed std::regex::grep which makes the regex POSIX ERE compliant, and that regex flavor does not support lazy quantifiers.
    smatch m; 
    
    while(std::regex_search(inputStr, m, regexp, std::regex_constants::match_default))
    {
        std::cout<<"String that matches the pattern: "<< m.str() << std::endl;
        inputStr = m.suffix();
    }
    
    return 0;
}

有用链接:

c11-regex-non-greedywhat-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions

相关问题