C++ [正则表达式] 如何提取给定的字符值

c++ [regex] how to extract given char value

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

如何提取数字值?

std::regex legit_command("^\([A-Z]+[0-9]+\-[A-Z]+[0-9]+\)$");
std::string input;

假设用户输入

(AA11-BB22)

我要得到

first_character = "aa"
first_number = 11
secondt_character = "bb"
second_number = 22

您可以使用捕获组。在下面的示例中,我用(AA11-BB22)替换了(AA11+BB22)以匹配您发布的正则表达式。请注意,只有当整个字符串与模式匹配时,regex_match才会成功,因此不需要行断言的开头/结尾(^$(。

#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
const string input = "(AA11-BB22)";
const regex legit_command("\(([A-Z]+)([0-9]+)-([A-Z]+)([0-9]+)\)");
smatch matches;
if(regex_match(input, matches, legit_command)) {
cout << "first_character  " << matches[1] << endl;
cout << "first_number     " << matches[2] << endl;
cout << "second_character " << matches[3] << endl;
cout << "second_number    " << matches[4] << endl;
}
}

输出:

$ c++ main.cpp && ./a.out 
first_character  AA
first_number     11
second_character BB
second_number    22