通过一个简单的示例了解 c++ 正则表达式
Understanding c++ regex by a simple example
我写了以下简单的例子:
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string str("1231");
std::regex r("^(\d)");
std::smatch m;
std::regex_search(str, m, r);
for(auto v: m) std::cout << v << std::endl;
}
演示
并对其行为感到困惑。如果我从那里正确理解了match_result
的目的,那么应该打印唯一的1
。实际上:
如果成功,则它不为空,并包含一系列sub_match 对象:第一个sub_match元素对应于整个匹配, 并且,如果正则表达式包含要匹配的子表达式 ([...])
传递给函数的字符串与正则表达式不匹配,因此我们不应该有the entire match
。
我错过了什么?
您仍然可以获得整个匹配项,但整个匹配项不适合整个字符串,它适合整个正则表达式。
例如,考虑一下:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string str("1231");
std::regex r("^(\d)\d"); // entire match will be 2 numbers
std::smatch m;
std::regex_search(str, m, r);
for(auto v: m)
std::cout << v << std::endl;
}
输出:
12
1
整个匹配项(第一个sub_match)是整个正则表达式匹配的对象(字符串的一部分)。
第二个sub_match是第一个(也是唯一一个)捕获组
查看您的原始正则表达式
std::regex r("^(\d)");
|----| <- entire expression (sub_match #0)
std::regex r("^(\d)");
|---| <- first capture group (sub_match #1)
这就是两个sub_matches的来源。
从这里开始
Returns whether **some** sub-sequence in the target sequence (the subject)
matches the regular expression rgx (the pattern). The target sequence is
either s or the character sequence between first and last, depending on
the version used.
因此regex_search将在输入字符串中搜索与正则表达式匹配的任何内容。整个字符串不必匹配,只需匹配其中的一部分。
但是,如果要使用 regex_match,则整个字符串必须匹配。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- 通过一个简单的示例了解 c++ 正则表达式