C ++ Regex to match words without punctuation

I searched, found nothing. It is in the interest of no longer wasting time for the answer to be obvious to someone else, I ask here. So far, only the site has been useful: http://softwareramblings.com/2008/07/regular-expressions-in-c.html , but the samples are too simplistic. I am using Visual Studio 2010.

#include <regex> [...] string seq = "Some words. And... some punctuation."; regex rgx("\w"); smatch result; regex_search(seq, result, rgx); for(size_t i=0; i<result.size(); ++i){ cout << result[i] << endl; } 

Expected Result:

Some
the words
AND
some
punctuation

Thanks.

+4
source share
2 answers

A few things here.

First, your regex string must have escape code \ . Its still C ++ - a string, after all.

 regex rgx("\\w"); 

In addition, the regular expression \w matches only one character of the word. If you want to combine the whole word, you need to use:

 regex rgx("\\w+"); 

Finally, to iterate over all possible matches, you need to use an iterator. Here is a complete working example:

 #include <regex> #include <string> #include <iostream> using namespace std; int main() { string seq = "Some words. And... some punctuation."; regex rgx("\\w+"); for( sregex_iterator it(seq.begin(), seq.end(), rgx), it_end; it != it_end; ++it ) cout << (*it)[0] << "\n"; } 
+3
source

Try the following:

 string seq = "Some words. And... some punctuation."; regex rgx("(\\w+)"); regex_iterator<string::iterator> it(seq.begin(), seq.end(), rgx); regex_iterator<string::iterator> end; for (; it != end; ++it) { cout << it->str() << endl; } 
+1
source

Source: https://habr.com/ru/post/1337430/


All Articles