【发布时间】:2018-12-12 14:40:08
【问题描述】:
对 c++ 正则表达式库非常陌生。
我们正在尝试解析一行
*10 abc
我们想将此行解析/拆分为仅两个标记:
10
abc
我尝试了多种方法,例如 regex_search,但我确实得到了 3 个匹配项。第一个匹配是整个匹配,第二个,第三个是子序列匹配。我的问题是
我们怎样才能从上面的字符串中只得到两个匹配项(10 和 abc)。我尝试过的快照:
#include <regex>
#include <iostream>
int main() {
const std::string t = "*10 abc";
std::regex rgxx("\\*(\\d+)\\s+(.+)");
std::smatch match;
bool matched1 = std::regex_search(t.begin(), t.end(), match, rgxx);
std::cout << "Matched size " << match.size() << std::endl;
for(int i = 0 ; i < match.size(); ++i) {
std::cout << i << " match " << match[i] << std::endl;
}
}
输出:
Matched size 3
0 match *10 abc
1 match 10
2 match abc
0 匹配是我不想要的。
我也愿意使用 boost 库/正则表达式。谢谢。
【问题讨论】:
-
正则表达式对于这样一个简单的解析来说太过分了。只需跳过第一个字符,复制到第一个空格实例,跳过空格,然后复制其余部分。正确使用
std::string只需大约四行代码。
标签: c++