【发布时间】:2020-06-14 09:45:47
【问题描述】:
我想同时做两件事:将字符串与模式匹配并提取组。
字符串由空格和数字组成。我想将字符串与此模式匹配。此外,我想使用 std::smatch 提取数字(不是数字,仅单个数字)。
我尝试了很多,但没有成功。
对于骗子猎人:我检查了很多关于 SO 的答案,但我找不到解决方案。
然后我尝试使用std::sregex_token_iterator。结果也让我感到困惑。在
#include <string>
#include <regex>
#include <vector>
#include <iterator>
const std::regex re1{ R"(((?:\s*)|(\d))+)" };
const std::regex re2{ R"(\s*(\d)\s*)" };
int main() {
std::string test(" 123 45 6 ");
std::smatch sm;
bool valid1 = std::regex_match(test, sm, re1);
std::vector<std::string> v(std::sregex_token_iterator(test.begin(), test.end(), re2), {});
return 0;
}
向量不仅包含数字,还包含空格。我想只有数字。
smatch 不包含任何数字。
我知道,我可以先从字符串中删除所有空格,但应该有更好的一步解决方案。
什么是正确的正则表达式 1. 将字符串与我描述的模式匹配 2. 将所有单个数字提取到 smatch 中?
【问题讨论】:
-
试试
\s*\d,它会匹配0+个空格,然后是个位数 -
@MichałTurczyn:抱歉,这行不通。