C++实践:正则表达式解析声卡参数
C++实践:正则表达式解析声卡参数
在Java中的正则表达式使用的https://www.txt2re.com/直接生成的,而在C++中txt2re并没有使用C++11中自带的正则库,而是使用的别的库,这么一来,如果想使用C++11中自带的正则库就用不了txt2re了。凭着感觉硬吞下来了。C++11来解析声卡参数。[txt2re还是很好用的][1]。
//============================================================================
// Name : CppPro.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include
#include
#include
using namespace std;
/**
* 在构造函数中
*/
class Card {
public:
int getId() const {
return id;
}
private:
int id;
string name;
class Device {
int id;
};
};
string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
if (first == string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}
/**
* 启动一个Loop接收客户端命令
*/
int main() {
std::string id;
std::string name;
smatch sm; // 存放string结果的容器
std::string txt = " 0 [PCH ]: HDA-Intel - HDA Intel PCH";
std::string re1 = "( )"; // Any Single Character 1
std::string re2 = "(\\d+)"; // Integer Number 1
std::string re3 = "( )"; // Any Single Character 2
std::string re4 = "(\\[.*?\\])"; // Square Braces 1
std::string re5 = "(:)"; // Any Single Character 3
std::string re6 = "( )"; // Any Single Character 4
if (regex_search(txt, sm, regex(re1 + re2 + re3 + re4 + re5 + re6))) {
id = sm[2];
name = sm[4];
name = name.substr(1, name.length() - 2);
name = trim(name);
}
cout<< "name: " << name << " id: " << id << endl;
}
运行结果:
name: PCH id: 0