2

I want to extract only those words within double quotes. So, if the content is:

Would "you" like to have responses to your "questions" sent to you via email?

The answer must be

1- you 2- questions

user522745
  • 161
  • 1
  • 2
  • 7

3 Answers3

2
std::string str("test \"me too\" and \"I\" did it");
std::regex rgx("\"([^\"]*)\""); // will capture "me too"
std::regex_iterator current(str.begin(), str.end(), rgx);
std::regex_iterator end;
while (current != end)
    std::cout << *current++;
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • @user522745 - right. Thanks. Fixed. (I always leave out that `*` the first time I write a regular expression like this one) – Pete Becker Feb 23 '13 at 15:20
  • Very interesting, however how would you match something like var ABC = "" ? I tried many examples, but none seem to fit... – Mecanik Apr 02 '18 at 10:42
  • Why it can only run std::cout << current->str(); current++; instead of std::cout << *current++; on my test? – MathArt Dec 02 '21 at 09:49
1

If you really want to use Regex, you can do it like so:

#include <regex>
#include <sstream>
#include <vector>
#include <iostream>

int main() {
    std::string str = R"d(Would "you" like to have responses to your "questions" sent to you via email?)d";
    std::regex rgx(R"(\"(\w+)\")");
    std::smatch match;
    std::string buffer;
    std::stringstream ss(str);
    std::vector<std::string> strings;
    //Split by whitespaces..
    while(ss >> buffer) 
        strings.push_back(buffer);
    for(auto& i : strings) {
        if(std::regex_match(i,match, rgx)) {
            std::ssub_match submatch = match[1];
            std::cout << submatch.str() << '\n';
        }
    }
}

I think only MSVC and Clang supposedly support though, otherwise you can use boost.regex like so.

Rapptz
  • 20,807
  • 5
  • 72
  • 86
0

Use the split() function from this answer then extract odd-numbered items:

std::vector<std::string> itms = split("would \"you\" like \"questions\"?", '"');
for (std::vector<std::string>::iterator it = itms.begin() + 1; it != itms.end(); it += 2) {
    std::cout << *it << endl;
}
Community
  • 1
  • 1