谷歌re2 namedcapture,如何解析c ++中的结果?

时间:2011-04-26 13:54:33

标签: c++ regex re2

使用google re2库进行正则表达式我还没有找到解决结果的方法!

这是一个简短的例子

bool b_matches ;
string s_teststr = " aaaaa flickr bbbb";
RE2 re("(?P<flickr>flickr)|(?P<flixster>flixster)");
assert(re.ok()); // compiled; if not, see re.error();
b_matches = RE2::FullMatch(s_teststr, re);

  b_matches = RE2::FullMatch(s_teststr, re);

// then,
re.NumberOfCapturingGroups() //-> always give me 2

 re.CapturingGroupNames(); //-> give me a map with id -> name (with 2 elements)

re.NamedCapturingGroups() //-> give me a map with name -> id (with 2 elements)

我必须知道只有flickr匹配了吗?

谢谢,

弗朗西斯

---经过一些更多的测试后,我没有找到一个关于命名捕获的解决方案,只有我找到工作的方式给我提取的文本,就是这个。

string s_teststr = "aaa  hello. crazy world bbb";
std::string word[margc];
RE2::Arg margv[margc];
RE2::Arg * margs[margc];
int match;
int i;

    for (i = 0; i < margc; i++) {
        margv[i] = &word[i];
        margs[i] = &margv[i];
    }
   string s_rematch = "((?P<a>hello\\.)(.*)(world))|(world)";
  match = RE2::PartialMatchN(s_teststr.c_str(), s_rematch.c_str(), margs, margc);
cout << "found res = " << match << endl;
  for (int i = 0; i < margc; i++) {
        cout << "arg[" << i << "] = " << word[i] << endl;
    }

--------这会给我输出:

  

发现res = 1 arg [0] =你好。疯   世界arg [1] =你好。 arg [2] =疯了   arg [3] = world arg [4] =

用字符串匹配的第二部分测试...

string s_rematch = "((?P<a>hello\\.d)(.*)(world))|(world)";

---我得到了输出:

  

foudn res = 1   arg [0] =   arg [1] =   arg [2] =   arg [3] =   arg [4] =世界

我的问题是名字捕获 - &gt; a&lt; ---永远不会出来,输出应该被清除(在不敏感匹配的情况下小写,从添加的兼容字符中删除,...)并再次对地图处理,因为我没有给我的命名捕获键而不是此preg的值

1 个答案:

答案 0 :(得分:0)

您可以传入一个字符串,以便在成功时填充。例如:

std::string matchedValue;

if (RE2::FullMatch(s_teststr, re, &matchedValue))
{
    if (matchedValue.empty())
    {
        //not flickr
    }
}
else
{
    // matchedValue.empty() == true
}
相关问题