I have a string:
"hello 1, hello 2, hello 17, and done!"
And I want to apply this regular expression repeatedly to it:
hello ([0-9]+)
And be able to iterate through the matches and their capture groups somehow. I've used the "regex" stuff successfully in c++0x to find the first match for something in a string and inspect the contents of the capture group; however, I'm not sure how to do this multiple times on a string until all the matches are found. Help!
(Platform is visual studio 2010, in case it matters.)
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.
For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter. In a character set a ^ character negates the following characters.
Don't use regex_match, use regex_search. You can find examples here: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339.
This should do the trick (notice I'm typing directly in the browser, didn't compile it):
#include <iostream>
#include <regex>
int main()
{
// regular expression
const std::regex pattern("hello ([0-9]+)");
// the source text
std::string text = "hello 1, hello 2, hello 17, and done!";
const std::sregex_token_iterator end;
for (std::sregex_token_iterator i(text.cbegin(), text.cend(), pattern);
i != end;
++i)
{
std::cout << *i << std::endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With