c++ - c++ [regex] 如何提取给定的char值
问题描述
如何提取数字数值?
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
字符串与模式匹配时才会成功,因此不需要行首/行尾断言 ( and )。^
$
#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