C++11 场比赛中的正则表达式匹配
C++11 regex matches within matches
是否可以遍历所有匹配项,包括匹配项中的匹配项?
我正在尝试从我的字符串中提取oook outside
以o
开头的子字符串,这些子字符串以不同的字符结尾:即 oook
、ook
、ok
和ou
。
我认为以下代码可以做到这一点:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
string s = "oook outside";
regex e("o+[a-z]");
sregex_iterator it(s.begin(), s.end(), e);
sregex_iterator it_end;
while (it != it_end) {
cout << it->str() << endl;
it++;
}
return 0;
}
相反,它只打印oook
和ou
。
匹配所有内容,但不消耗任何内容。
引擎将在每场比赛
中将位置提高 1 个消耗字符。
若要查看匹配项,请将其包装到捕获组中。
(?=(o+[a-z]))
扩大
(?=
( o+ [a-z] ) # (1)
)
如果引擎没有碰到它,那么你总是可以手动消耗 1。
要匹配它,但消耗 1 次使用:
(?=(o+[a-z]))o
扩大
(?=
( o+ [a-z] ) # (1)
)
o
两者是等效的。从捕获组 1 获取结果。
比赛
** Grp 0 - ( pos 0 , len 0 ) EMPTY
** Grp 1 - ( pos 0 , len 4 )
oook
--------------------
** Grp 0 - ( pos 1 , len 0 ) EMPTY
** Grp 1 - ( pos 1 , len 3 )
ook
--------------------
** Grp 0 - ( pos 2 , len 0 ) EMPTY
** Grp 1 - ( pos 2 , len 2 )
ok
--------------------
** Grp 0 - ( pos 5 , len 0 ) EMPTY
** Grp 1 - ( pos 5 , len 2 )
ou
知道了!
int main() {
string s = "oook outside";
smatch m;
regex e("(?=(o+[a-z]))o"); // "o+[a-z]";
while (regex_search(s, m, e)) {
cout << m[1] << endl;
s = m.suffix();
}
return 0;
}
谢谢大家!
相关文章:
- 如何在 c++11 中使用正则表达式找到确切的子字符串?
- 如何将Javascript正则表达式转换为C++11正则表达式
- C++11 (MSVS2012) 正则表达式在多行 std::string 中查找文件名
- C 11正则表达式和字符串U8前缀
- C++11 正则表达式匹配不以句点结尾的完整单词
- 有条件地忽略 c++11 正则表达式中的大小写
- C++11 中的默认正则表达式引擎是什么?
- 为什么 pcre 正则表达式比 c++11 正则表达式快得多
- 在 C++11 下使用正则表达式
- C++11 正则表达式行尾不匹配
- C++11正则表达式:在替换字符串中捕获组后的数字
- 为什么 C++11 正则表达式(libc ++ 实现)如此缓慢?
- C++11 CMake:正则表达式失败
- 如何获得与 C++11 或 Boost 匹配的正则表达式长度
- Regex分组与C++11正则表达式库匹配
- 使用 libc++ 正则表达式库匹配"beginning-of-line" (C++11)
- C++11 中的正则表达式
- C++11正则表达式不匹配任何内容
- 将 C++11 正则表达式与 gcc 4.8.2 一起使用时会出现奇怪的结果(但适用于 Boost 正则表达式)
- C++11 正则表达式与字符串不匹配