【问题标题】:Regex in C++ to fetch from a regex expression a string in any part of the textC++ 中的正则表达式从正则表达式中获取文本任何部分的字符串
【发布时间】:2012-03-22 12:51:46
【问题描述】:

例子:

这里是字符串:"blablabla123:550:404:487blablabla500:488:474:401blablablabla"

这是我正在使用的:

string reg = "(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})";

这显然不起作用,因为它正在寻找以数字开头, 我也想获取所有结果,但我不知道该怎么做,即使我找了很多。 :/

我想要 2 个数组:

数组 1:应该返回 [1] = "123"; [2] = "550"; [3] = "404"; [4] = “487”;
数组 2:应该返回 [1] = "500"; [2] = "488"; [3] = "474"; [4] = "401";

#include <regex>
#include <iostream>
#include <string>

#include <conio.h>
using namespace std;

typedef std::tr1::match_results<std::string::const_iterator> str_iterator;
int main () {
    str_iterator res;

string regex = "(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})";
string str = "blablabla123:550:404:487blablabla500:488:474:401blablablabla";
const std::tr1::regex pattern(regex.c_str());
bool valid = std::tr1::regex_match(str, res, pattern);
//res is gonna be an array with the match results
if(valid){
    printf("Matched with size of %d\n", res.size());
    printf("Result 1: %s",res[1]);
    printf("Result 2: %s",res[2]);
    printf("Result 3: %s",res[3]);
    printf("Result 4: %s",res[4]);
}else{
    printf("Not Matched");
}
_getch();
return 0;
}

【问题讨论】:

    标签: c++ regex tr1


    【解决方案1】:

    regex_match 将尝试匹配 整个 字符串。显然,在您的情况下,结果将是错误的(不匹配)。

    尝试改用regex_search

    【讨论】:

    • 是的,这听起来很对,我希望你已经解释了我如何使用 regex_search 来做到这一点,但既然你没有,它应该是另一个话题,所以就这样吧,我希望你能答案:stackoverflow.com/questions/9823367/…
    【解决方案2】:

    这个呢:

    [^\d]*(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]*
    

    这很糟糕,但我们将检索 8 个由任何其他字符分隔的数字。

    group(0)    group(1)    group(2)    group(3)    group(4)    group(5)    group(6)    group(7)    
    123           550         404         487         500         488           474         401
    

    否则,您可以修改字符串,用: 替换每个非数字,这将为您提供: :::::::::123:550:404:487:::::::::500:488:474:401:::::::::::: 您只需通过解析字符串来保留非空值。但这只有在您确定没有空值时才有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多