在提升匹配结果中查找不匹配
Find mismatch in boost match results
我正在使用 boost::regex_match,我正在尝试找到一个函数来获取正则表达式停止匹配的位置。我在 boost::match_results 对象中找不到任何属性,但有几个代码片段,其中 boost::regex_search 用于显示子匹配项。我的实施是否走在正确的道路上,还是我必须做一些不同的事情才能实现这一目标?我的代码如下所示:
int main(int args, char** argv)
{
boost::match_results<std::string::const_iterator> what;
if(args == 3)
{
std::string text(argv[1]);
boost::regex expression(argv[2]);
std::cout << "Text : " << text << std::endl;
std::cout << "Regex: " << expression << std::endl;
if(boost::regex_match(text, what, expression, boost::match_default) != 0)
{
int i = 0;
for(boost::match_results<std::string::const_iterator>::const_iterator it=what.begin(); it!=what.end(); ++it)
{
std::cout << "[" << (i++) << "] " << it->str() << std::endl;
}
std::cout << "Matched!" << std::endl;
}
else
{
std::string::const_iterator start = text.begin();
std::string::const_iterator end = text.end();
while(boost::regex_search(start, end, what, expression))
{
std::string submatch(what[1].first, what[1].second);
std::cout << submatch << std::endl;
start = what[0].second;
}
std::cout << "Didn't match!" << std::endl;
}
} //if(args == 3)
else
{
std::cout << "Invalid usage! $> ./boost-regex <text> <regex>" << std::endl;
}
return 0;
}
输出:
$> ./boost_regex "We're building it up to burn it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burn it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to burn it down
[1] building it up
[2] to
[3] burn it down
Matched!
$> ./boost_regex "We're building it up to burm it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
Didn't match!
对于最后一个输入,我希望有类似于以下内容的内容:
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to
[1] building it up
[2] to
Didn't match!
提前感谢...
首先,您在示例中的正则表达式存在问题。 因为它无法匹配(burn.*)
子组,所以整个正则表达式无法匹配任何内容,并且不返回任何结果。 在(burn.*)
之后添加一个"?"将使前两个子组匹配,而第三个子组不匹配。
我会 rubular.com 结帐,它是调整正则表达式并实时观察它们工作的好工具。
要测试子组是否参与匹配,您需要检查 for 循环中的sub_match::matched
布尔变量,如果子组匹配,则为 true。 在此处查看有关 Boost::Submatch 的文档
希望这有所帮助,这实际上是我的第一个 Stackoverflow 帖子、答案或评论。 :)
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 在使用累加时,C++中的运算符+不匹配
- C++ 与操作员不匹配<<
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 与'operator='不匹配(操作数类型'String'且"void")
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- g++ -I 和 -L 命令来查找不起作用的 .hpp 文件
- C4018:类内有符号、无符号不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- RE2 不匹配非 ASCII 字符
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 查找不存在的键时,unordered_map返回什么
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 查找匹配的输入,并返回匹配的输入和不匹配的输入
- 重载函数查找轮廓的实例与参数列表不匹配
- 搜索字符串(只查找完全匹配的字符串,不忽略大写或小写字符
- 在提升匹配结果中查找不匹配