简体   繁体   English

如何匹配以“!”开头的十进制数字 在C ++中

[英]How to match decimal numbers starting with '!' in C++

How do I match all the decimal numbers starting with "!" 如何匹配以“!”开头的所有十进制数字 (bang) in the given string? (轰)在给定的字符串? I have written the following code but it fails with an assert 我已经写了下面的代码,但是它失败并带有断言

#include<iostream>
#include<regex>

int main()
{
    std::string s1("{!112,2,3}");
    std::regex e(R"(\!\d+)", std::regex::grep);

    std::cout << s1 << std::endl;

    std::sregex_iterator iter(s1.begin(), s1.end(), e);
    std::sregex_iterator end;

    while(iter != end)
    {
        std::cout << "size: " << iter->size() << std::endl;

        for(unsigned i = 0; i < iter->size(); ++i)
        {
            std::cout << "the " << i + 1 << "th match" << ": " << (*iter)[i] << std::endl;
        }
        ++iter;
    }
}

assert 断言

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

First, make sure you are using the latest GCC compiler. 首先,请确保您使用的是最新的GCC编译器。

Then use R"(!(\\d+))" pattern that matches an exclamation mark and then captures one or more digits Iinto Group 1. 然后使用与感叹号匹配的R"(!(\\d+))"模式,然后捕获Iinto组1中的一个或多个数字。

Then just grab (*iter)[1] that holds your values while iterating the matches. 然后只需在迭代匹配时抓取(*iter)[1]保存您的值。

See the C++ demo : 参见C ++演示

#include<iostream>
#include<regex>
int main() {
   std::string s1("{!112,2,3} {!346,765,8}"); 
   std::regex e(R"(!(\d+))"); 
   std::cout << s1 << std::endl; 
   std::sregex_iterator iter(s1.begin(), s1.end(), e); std::sregex_iterator end;   
   while(iter != end) { 
       std::cout << "Value: " << (*iter)[1] << std::endl; 
       ++iter; 
    }
}

Output: 输出:

{!112,2,3} {!346,765,8} 
Value: 112
Value: 346

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM