Reputation: 8499
I tested the RegEx [BCGRYWbcgryw]{4}\[\d\]
on that site and it seems ok to find match in the following BBCC[0].GGRY[0].WWWW[soln]. It match with BBCC[0] and GGRY[0].
But when I tried to code and debug that matching, the sm
value stay empty.
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, ", "));
Where am I wrong ?
Upvotes: 0
Views: 540
Reputation: 171413
If you don't want to match the whole input sequence then use std::regex_search
not 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;
}
N.B. this also uses raw strings to simplify the regular expression.
Upvotes: 1
Reputation: 8499
I finally get it work, with ()
to define a capture group and I use regex_iterator
to find all sub-string matching the pattern.
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;
}
The output is:
Whole string [0].GGRY
First sub-group [0].GGRY
Whole string [0].WWWW
First sub-group [0].WWWW
Upvotes: 0