Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the new c++0x regex object to match repeatedly within a string?

Tags:

c++

regex

c++11

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.)

like image 958
Colen Avatar asked Apr 07 '11 19:04

Colen


People also ask

What does * do in regex?

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.

Can you return a string in regex?

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.

What is the use of given statement in regular expression a za Z?

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.


1 Answers

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;
}
like image 105
Marius Bancila Avatar answered Oct 26 '22 11:10

Marius Bancila