afa*_*lco 5 c++ regex visual-studio-2010
我是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;
Run Code Online (Sandbox Code Playgroud)
修改后的代码:
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;
Run Code Online (Sandbox Code Playgroud)
奇怪的是修改后的代码的一部分有效,而下一部分则导致异常.我甚至尝试使用mr [0] .str()但我得到了相同的错误消息.你能帮我解决这个问题吗?
Mat*_* M. 10
问题是临时问题之一.
smatch 将包含迭代器到您要搜索的字符串中.
regex_search(string("xabcd"), mr, rx)创建一个临时字符串,在该处死亡;.
因此,当您mr在下一行使用时,它指的是无效的内存.本string应该活得比较长mr.
| 归档时间: |
|
| 查看次数: |
3007 次 |
| 最近记录: |