C++正则表达式和占位符
C++ RegExp and placeholders
我在 C++11 MSVC2013,我需要从文件名中提取一个数字,例如:
string filename = "s 027.wav";
如果我用Perl,Java或Basic编写代码,我会使用正则表达式,像这样的东西可以在Perl5中解决问题:
filename ~= /(d+)/g;
我会在占位符变量 $1
中有数字"027"。
我也可以在C++这样做吗?或者您可以建议一种不同的方法来从该字符串中提取数字 027?另外,我应该将生成的数字字符串转换为整数标量,我认为atoi()
是我需要的,对吧?
您可以在
C++中执行此操作,从 C++11 开始,使用 regex
中找到的类集合。它与您在其他语言中使用的其他正则表达式非常相似。下面是一个简洁的示例,说明如何在发布的文件名中搜索数字:
const std::string filename = "s 027.wav";
std::regex re = std::regex("[0-9]+");
std::smatch matches;
if (std::regex_search(filename, matches, re)) {
std::cout << matches.size() << " matches." << std::endl;
for (auto &match : matches) {
std::cout << match << std::endl;
}
}
至于将027
转换为数字,您可以像您提到的那样使用 atoi
(从 cstdlib
),但这将存储值27
,而不是027
。如果你想保留0
前缀,我相信你需要把它作为一个string
。 match
上面是一个sub_match
,因此,提取一个string
并转换为const char*
以进行atoi
:
int value = atoi(match.str().c_str());
好的,我使用 std::regex 解决了这个问题,由于某种原因,我在尝试修改我在网络上找到的示例时无法正常工作。它比我想象的要简单。这是我写的代码:
#include <regex>
#include <string>
string FileName = "s 027.wav";
// The search object
smatch m;
// The regexp /d+/ works in Perl and Java but for some reason didn't work here.
// With this other variation I look for exactly a string of 1 to 3 characters
// containing only numbers from 0 to 9
regex re("[0-9]{1,3}");
// Do the search
regex_search (FileName, m, re);
// 'm' is actually an array where every index contains a match
// (equally to $1, $2, $2, etc. in Perl)
string sMidiNoteNum = m[0];
// This casts the string to an integer number
int MidiNote = atoi(sMidiNoteNum.c_str());
这是一个使用 Boost 的示例,替换正确的命名空间,它应该可以工作。
typedef std::string::const_iterator SITR;
SITR start = str.begin();
SITR end = str.end();
boost::regex NumRx("\d+");
boost::smatch m;
while ( boost::regex_search ( start, end, m, NumRx ) )
{
int val = atoi( m[0].str().c_str() )
start = m[0].second;
}
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 正则表达式 获取两个换行符之间的文本
- 不同换行符的正则表达式
- 如何忽略正则表达式(C++)中的换行符
- C++正则表达式和占位符
- 学习提升::正则表达式,匹配通配符
- 正则表达式:从ANSI C++样式的左大括号(换行符)切换到K&R样式(与语句相同的行)
- std::正则表达式等同于'/g'全局修饰符