我试图在字符串中找到几个数字位置。我只能获取最后一位或之前指定的位数:
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::string s("aaabbbccd123456eeffgg");
std::smatch match;
std::regex braced_regex("(\\w+)(\\d{2,})(\\w+)");
std::regex plus_regex("(\\w+)(\\d+)(\\w+)");
auto printer = [](auto& match) {
std::ssub_match sub(match);
std::string match_substring(sub.str());
std::cout << match_substring << '\n';
};
std::regex_match(s, match, braced_regex);
std::cout << "Number of braced matches: " << match.size() << '\n';
std::for_each(match.begin(), match.end(), printer);
std::regex_match(s, match, plus_regex);
std::cout << "Number of plus matches: " << match.size() << '\n';
std::for_each(match.begin(), match.end(), printer);
return 0;
}
结果:
Number of braced matches: 4
aaabbbccd123456eeffgg
aaabbbccd1234
56
eeffgg
Number of plus matches: 4
aaabbbccd123456eeffgg
aaabbbccd12345
6
eeffgg
如何从提供的字符串中获取整个数字序列,即 123456?
最佳答案
([a-zA-Z]+)(\\d{2,})([a-zA-Z]+)
你可以试试这个。\w
===[a-zA-Z0-9_]
。所以\w+
将匹配max它可以。所以它让 \d{2,}
只有 2。
或
(\\w+?)(\\d{2,})(\\w+)
使第一个 \w
不贪婪。请参阅live demo .
关于c++ - 如何获取未知数量的正则表达式匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27419136/