为什么使用“cmatch”的 C++ 正则表达式代码会引发“smatch”异常?

2024-02-26

我是 C++ 正则表达式的新手,无法让它们使用字符串而不是 char*。到目前为止我看到的例子都是针对 c 字符串的。

我真正的程序,我什至不会尝试在这里展示,使用子匹配,但我不能 让它们工作,所以我尝试修改一个非常简单的工作示例,但它也不起作用。我使用 Visual Studio 2010 Ultimate。

原始工作代码:

const char *first = "abcd"; 
const char *last = first + strlen(first); 
std::cmatch mr; 
std::regex rx("abc"); 
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;

std::cout << "search(f, l, \"abc\") == " << std::boolalpha 
          << regex_search(first, last, mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl; 

std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
          << regex_search("xabcd", mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

修改后的代码:

const string first = "abcd";     // char * => string
std::smatch mr;                  // cmatch => smatch
std::regex rx(string("abc")); 
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;

               // this works:
std::cout << "search(f, l, \"abc\") == " << std::boolalpha 
          << regex_search(first, mr, rx) << std::endl; 
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl; 

               // after the next line executes mr seems good to me:
               // mr[0] = {3, matched:true, first="abcd", second="d",...}
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
          << regex_search(string("xabcd"), mr, rx) << std::endl; 
               // but the following line gives the error
               // "Debug assertion failed"
               // Expression: string iterators incompatible
std::cout << "  matched: \"" << mr.str() << "\"" << std::endl;

奇怪的是,修改后的代码的一部分可以工作,而下一部分会引发异常。我什至尝试使用 mr[0].str() 但收到相同的错误消息。你能帮我解决这个问题吗?


这个问题是暂时的问题之一。

smatch将包含您正在搜索的字符串中的迭代器。

regex_search(string("xabcd"), mr, rx)创建一个临时字符串dies at the ;.

因此当你使用时mr在下一行,它指的是无效的内存。这string应该活得比mr.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么使用“cmatch”的 C++ 正则表达式代码会引发“smatch”异常? 的相关文章

随机推荐