regex_match找不到任何匹配项

regex_match doesn't find any matching

本文关键字:任何匹 找不到 match regex      更新时间:2023-10-16

我在该站点上测试了RegEx [BCGRYWbcgryw]{4}[d],在以下BBCC[0]、GGRY[0]、WWWW[soln]中找到匹配似乎是可以的。它与BBCC[0]和GGRY[0]匹配。

但是,当我尝试对匹配进行编码和调试时,sm值保持为空。

    regex r("[BCGRYWbcgryw]{4}\[\d\]");
string line; in >> line;
smatch sm;
regex_match(line, sm, r, regex_constants::match_any);
copy(boost::begin(sm), boost::end(sm), ostream_iterator<smatch::value_type>(cout, ", "));

我哪里错了?

如果不想匹配整个输入序列,请使用std::regex_search而不是std::regex_match

#include <iostream>
#include <regex>
#include <iterator>
#include <algorithm>
int main()
{
  using namespace std;
  regex r(R"([BCGRYWbcgryw]{4}[d])");
  string line = "BBCC[0].GGRY[0].WWWW[soln]";
  smatch sm;
  regex_search(line, sm, r, regex_constants::match_any);
  copy(std::begin(sm), std::end(sm), ostream_iterator<smatch::value_type>(cout, ", "));
  cout << endl;
}

注意:这也使用原始字符串来简化正则表达式。

我终于开始工作了,用()定义一个捕获组,用regex_iterator找到所有与模式匹配的子字符串。

std::regex rstd("(\[[0-9]\].[BCGRYWbcgryw]{4})");
std::sregex_iterator stIterstd(line.begin(), line.end(), rstd);
std::sregex_iterator endIterstd;
for (stIterstd; stIterstd != endIterstd; ++stIterstd)
{
    cout << " Whole string " << (*stIterstd)[0] << endl;
    cout << " First sub-group " << (*stIterstd)[1] << endl;
}

输出为:

Whole string [0].GGRY
First sub-group [0].GGRY
Whole string [0].WWWW
First sub-group [0].WWWW