c ++ [regex]如何提取给定的char值

时间:2018-06-18 05:05:05

标签: c++ regex string

如何提取数字值?

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

1 个答案:

答案 0 :(得分:2)

您可以使用捕获组。在下面的示例中,我将(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