c++ - C++ 中的正则表达式从正则表达式中获取文本任何部分中的字符串

标签 c++ regex tr1

例子:

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

这是我正在使用的:

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

这显然是行不通的,因为它正在寻找以数字开头的, 而且我也想获取所有结果,但我不知道该怎么做,尽管我为此寻找了很多。 :/

我想要 2 个数组:

Array 1: should return [1] = "123"; [2] = "550"; [3] = "404"; [4] = "487";
Array 2: should return [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;
}

最佳答案

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

尝试改用regex_search

关于c++ - C++ 中的正则表达式从正则表达式中获取文本任何部分中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9822653/

相关文章:

C++ 0x lambda按值捕获总是const?

Java匹配正则表达式并提取组oneliner

c++ - 哈希函数为一对long long?

c++ - 索引大于 64 位的哈希函数?

C++ 指向不在范围内的函数调用的指针

c++ - 穿过院子而不被淋湿

java - 使用 Regex 查找模式并用处理过的数据替换它们

c++ - 无法在 VS10 中订购 weak_ptr

c++ - 访问 stringstream 对象的关联字符串

正则表达式,匹配具有可选结尾的整个单词