c++oding="utf-8" ?>
regex_search默认只匹配首个数字,需用r"(\d+)"定位整数;支持负数用r"(-?\d+)",浮点数用r"(-?\d+.?\d*)",结果存smatch中,match[0].str()获取字符串并转整数。

regex_search 一次匹配一个数字
默认情况下 std::regex_search 只找第一个匹配,适合你只要首个数字的场景。注意它不自动跳过非数字字符——得靠正则本身定位数字:
- 用
R"(\d+)"匹配连续多位整数(\d在 C++11 regex 中等价于[0-9]) - 匹配结果存在
std::smatch中,match[0]是整个匹配串,match.str()拿字符串,std::stoi(match.str())转整数 - 别忘了加
std::regex_constants::ECMAScript标志(虽然通常是默认值,但显式写上更稳)
std::string s = "abc123def456";
std::regex re(R"(\d+)");
std::smatch match;
if (std::regex_search(s, match, re)) {
std::cout
<h3>regex_iterator 循环提取所有数字</h3>
<p>要拿全部数字,必须用 <code>std::sregex_iterator</code>。它本质是迭代器适配器,底层调用 <code>regex_search</code> 并自动更新搜索起点——但容易漏掉重叠匹配(比如 <code>"123"</code> 和 <code>"23"</code> 不会同时出现,因为 <code>\d+</code> 是贪婪且不回溯的):</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master"><img
src="https://img.php.cn/upload/skill/000/000/081/179051228971575.jpg" alt="C++ Code Review Master" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master" class="overflowclass">C++ Code Review Master</a>
<p class="overflowclass">组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。</p>
</div>
<a rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
- 构造时传入字符串起止迭代器和正则对象,别传错顺序(
s.begin(), s.end(), re) - 每次解引用得到
std::smatch,取it->str()即可 - 如果字符串里有负号或小数点,
\d+会失败;要支持负数得写R"(-?\d+)",浮点数则需R"(-?\d+\.?\d*)"(注意小数点要转义)
std::string s = "price: -12.5 and qty: 99";
std::regex re(R"(-?\d+\.?\d*)");
for (std::sregex_iterator it(s.begin(), s.end(), re); it != std::sregex_iterator(); ++it) {
std::cout str()
<h3>为什么 std::regex_match 总是失败?</h3>
<p><code>std::regex_match</code> 要求**整个字符串完全匹配**正则,不是“包含”。想用它提数字,得把正则写成 <code>R"(.*?(\d+).*)"</code> 并捕获第 2 组——但这绕远路,还容易因贪婪量词出错:</p>
- 常见误用:
regex_match("abc123", re)配R"(\d+)"→ 失败,因为"abc123"不全是数字 - 真正需要
regex_match的场景是验证格式,比如判断字符串是否「纯数字」:regex_match(s, std::regex(R"(\d+)")) - 提取任务一律优先选
regex_search或迭代器,别硬套match
性能和兼容性坑点
libstdc++(GCC 默认)的 std::regex 实现长期有性能问题和部分特性不支持(比如 lookbehind),Clang/libc++ 也直到较新版本才修复。实际项目中:
- 简单数字提取基本没问题,但别在循环里反复构造
std::regex对象——提前定义为 const static - 如果要处理 GBK/UTF-8 混合文本,
\d只认 ASCII 数字,不会匹配全角数字(如“123”),得手动写[0-9\uff10-\uff19] - 极端性能敏感场景(如日志解析),考虑用
std::find_first_of+ 手动扫描,比 regex 快一个数量级
正则提取数字本身不难,难的是想清楚你要的是“第一个”“全部”还是“特定位置”,以及数字是否带符号、小数、科学计数法——这些直接决定正则怎么写,而不是库怎么用。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










