In the regex_search function, the first matching result found is saved to a Smatch class.
However, if there are multiple matching results in the search string, you need to implement it yourself.
In Smatch, there are two members, the official documents are as follows:
Iterator First:
An iterator denoting the position of the the match.
Iterator second
An iterator denoting the position of the end of the match.
Therefore, the following method can be used to get a traversal search:
[CPP]View Plaincopy
- #include <string>
- #include <iostream>
- #include <boost\regex.hpp>
- int main ()
- {
- std::string str = "192.168.1.1";
- Boost::regex expression ("\\d+");
- Boost::smatch what;
- Std::string::const_iterator start = Str.begin ();
- Std::string::const_iterator end = Str.end ();
- While (Boost::regex_search (Start, end, what, expression))
- {
- Std::cout << what[0] << Std::endl;
- start = What[0].second;
- }
- return 0;
- }
The results are as follows:
[Plain]View Plaincopy
- 192
- 168
- 1
- 1
In boost, an iterator is also provided, named: Sregex_iterator, and the default constructor generates an end iterator. Use the following:
[CPP]View Plaincopy
- #include <string>
- #include <iostream>
- #include <boost\regex.hpp>
- int main ()
- {
- std::string str = "192.168.1.1";
- Boost::regex expression ("\\d+");
- Boost::sregex_iterator It (Str.begin (), str.end (), expression);
- Boost::sregex_iterator end;
- For (; it! = end; ++it)
- Std::cout << *it << Std::endl;
- return 0;
- }
The effect is the same as the previous example. If you do not need to traverse, only need to match, that is simpler: Boost::regex reg (Szreg);
BOOL R=boost::regex_match (SZSTR, Reg) or need to be placed in a cmatch: {Boost::cmatch mat;
Boost::regex Reg ("\\d+"); Find numbers in a string
if (Boost::regex_search (Szstr, Mat, Reg))
{
cout << "searched:" << mat[0] << Endl;
}
}
Traverse a search using boost Regex regex_search