【问题标题】:c++ [regex] how to extract given char valuec++ [regex] 如何提取给定的char值
【发布时间】:2018-11-26 21:56:47
【问题描述】:

如何提取数字数值?

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

【问题讨论】:

    标签: c++ regex string


    【解决方案1】:

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

    【讨论】:

    • 在括号表达式/字符类之外,- 没有任何特殊性,不应转义(因此我的编辑)。
    • 如何访问matches[2]和matches[4]将它们转换成int?
    • @user3770234 你可以使用std::stoi。请注意,如果值超出 int 的范围,它可能会引发异常(正则表达式不施加长度限制 - 例如,您可以使用 [0-9]{2} 来精确要求两位数)。 const int first_number = stoi(matches[2]);
    • 对不起 distrub,那么如何将 A 转换为数字为 0,我尝试使用 match[1] - 'A' 将给出 int 值
    猜你喜欢
    • 2017-08-16
    • 2022-01-12
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多