C++正则表达式和占位符

C++ RegExp and placeholders

本文关键字:占位符 正则表达式 C++      更新时间:2023-10-16

我在 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前缀,我相信你需要把它作为一个stringmatch上面是一个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;
}