代码之家  ›  专栏  ›  技术社区  ›  CroCo

如何考虑在正则表达式的数字中取点

  •  1
  • CroCo  · 技术社区  · 6 年前

    请看下面的正则表达式

    std::regex reg("[A][-+]?([0-9]*\\.[0-9]+|[0-9]+)");

    这将发现任何一个字母后跟浮点数。如果数字 A30. A30 . 我想强制正则表达式也考虑小数点。这可行吗?

    #include <iostream>
    #include <string>
    #include <regex>
    using namespace std;
    
    int main()
    {
    
        std::string line("A50. hsih Y0 his ");
        std::smatch match;
        std::regex reg("[A][-+]?([0-9]*\\.[0-9]+|[0-9]+)");   
    
        if ( std::regex_search(line,match,reg) ){
                cout << match.str(0) << endl;
    
            }else{
                cout << "nothing found" << endl;
            }
    
      return 0;
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Christophe    6 年前

    您要求点后面跟一个或多个(+)数字。只需将尾部ditigs更改为:

    std::regex reg("[A][-+]?([0-9]*\\.[0-9]*|[0-9]+)");   
    

    Demo

    std::regex reg("[A][-+]?([0-9]*\\.[0-9]+|[0-9]+\\.?)");   
    

    所以要么是尾随的数字,要么是后面有点的数字。

    Second demo

        2
  •  1
  •   Code Maniac    6 年前

    A[-+]?(?:[0-9]*\\.?(?:[0-9]+)?)
    
    • A -匹配 .
    • [-+]? + - . ( ? (可选)
    • (?:[0-9]*\\.?(?:[0-9]+)?)
      • (?:[0-9]*\\. -将匹配零个或多个数字,后跟 .
      • (?:[0-9]+)? -匹配一次或多次。(?(可选)

    Demo