【问题标题】:Regex: C++ extract text within double quotes正则表达式:C++ 提取双引号内的文本
【发布时间】:2013-02-23 23:20:46
【问题描述】:

我只想提取双引号内的那些单词。所以,如果内容是:

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

答案一定是

1- 你 2-问题

【问题讨论】:

  • 你必须使用正则表达式吗?没有,实现起来非常简单
  • 一个简单的正则表达式来捕获引号中的任何内容将是\"\w+\",尽管没有它也是可行的。
  • 是的,我测试了很多模式,但都错了

标签: c++


【解决方案1】:
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++;

【讨论】:

  • @user522745 - 对。谢谢。固定的。 (我第一次写这样的正则表达式时总是忽略*
  • 非常有趣,但是你将如何匹配 var ABC = "" 之类的东西?我尝试了很多示例,但似乎没有一个适合...
  • 为什么只能运行 std::cout str();当前++;而不是 std::cout
【解决方案2】:

如果你真的想使用正则表达式,你可以这样做:

#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';
        }
    }
}

我认为只有 MSVC 和 Clang 应该支持,否则你可以使用 boost.regex like so

【讨论】:

  • @H2CO3 不。除非我误会了。
  • @Rapptz - POSIX 具有带有 C 接口的正则表达式。
  • @H2CO3 - C++ 有正则表达式,从 TR1 开始,现在在 C++11 中成为主流。
【解决方案3】:

使用this answer 中的split() 函数,然后提取奇数项:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    相关资源
    最近更新 更多