Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Regex match for Any number of words?

by davido (Cardinal)
on Jan 16, 2022 at 19:48 UTC ( #11140510=note: print w/replies, xml ) Need Help??


in reply to Regex match for Any number of words?

C++ has had regular expressions (in some degree of support) in-language since C++11, which is now ten or eleven years old. Unless you have to use Boost for this, you may just want to fall back to the language-native implementations. As I was looking to remember how to retrieve matches I found the std::regex_iterator entity. And the example in the C++ reference online is close enough to what you're looking for: regex_iterator

#include <regex> #include <iterator> #include <iostream> #include <string> int main() { const std::string s = "Quick brown fox."; std::regex words_regex("[^\\s]+"); auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex); auto words_end = std::sregex_iterator(); std::cout << "Found " << std::distance(words_begin, words_end) << " words:\n"; for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; + std::string match_str = match.str(); std::cout << match_str << '\n'; } }

As you can see in the example, they're counting as a word anything that doesn't contain whitespace. You probably want to also exclude punctuation. So you would want to enumerate that in the character class. It gets harder when you want to deal with apostrophes, allowing them in words, while excluding single quoted constructs. That gets complicated fast.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140510]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2022-05-21 09:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (76 votes). Check out past polls.

    Notices?