c++ - 查找字母子串

标签 c++ regex gcc c++11 substring

我有以下字符串,我只想从中提取大于 1 的字母部分(字母子字符串):

  • %d. i.p.p. attendu --> attendu
  • 四月。专业知识 --> apr, 专业知识
  • n.c.p.c.谴责者 --> 谴责者

我正在尝试以下代码:

#include <regex>
#include <iostream>
void main()
{
    const std::string s = "% d. i.p.p. attendu";
    std::regex rgx("[a-zA-Z]{2,20}");
    std::smatch match;

    if (std::regex_search(s.begin(), s.end(), match, rgx))
        std::cout << "match: " << match[1] << '\n';
} 

但是当我运行代码时出现以下错误: 在抛出 'std::regex_error' what(): regex_error 实例后调用终止

你能帮帮我吗 谢谢你, 哈尼族。

好吧,我成功地使用了 boost,因为 gcc 的正则表达式是一个可憎的

#include <boost/regex.hpp>

void main()
{
        const std::string s = "% d. i.p.p. tototo attendu";
        boost::regex re("[a-zA-Z]{4,7}");
        boost::smatch matches;
        if( boost::regex_search( s, matches, re ) )
         {
               std::string value( matches[0].first, matches[0].second );
                cout << value << "  ";
          }
}

很好,我找到了 attendu,但输出只有 tototo。它不是递增的

返回值是“tototo attendu”我想知道我是否可以一次返回每个值而不是 1 个字符串

最佳答案

I was wondering if I can return each value at a time instead of 1 string

这样做的唯一方法似乎是通过 regex_iterator .下面是一个使用 Boost 的例子:

#include <boost/regex.hpp>
#include <iostream>

int main() {
    const std::string s = "% d. i.p.p. tototo attendu";
    boost::regex rgx("([a-zA-Z]{2,20})");
    boost::smatch match;

    boost::sregex_iterator begin{s.begin(), s.end(), rgx},
                           end{};

    for (auto&& i = begin; i != end; ++i)
        std::cout << "match: " << *i << '\n';
}

这会产生:

match: tototo
match: attendu

两件事:

  • main 的返回类型是总是 int。您的代码甚至不应该编译。
  • 我在您的(首先,这是正确的!)正则表达式周围添加了括号,以便它为每个匹配创建一个捕获。然后迭代器依次迭代每个匹配项。

关于c++ - 查找字母子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17345533/

相关文章:

java - 使用java中的正则表达式从下面的字符串中获取值

android - 获取错误 ld.exe : error: cannot find -lgnuSTL_shared in ndk on compiling tbb source files

c++ - 我如何将用户输入分成一个字符和一个整数?

java - 释放本地对象

javascript - 如何在具有正则表达式模式的匹配方法中使用变量

java - 如何使用分隔字符串 "#|#"分割字符串

c - c 中的 sqrt() 方法(Netbeans 编译器与 gcc)

c++ - 使用__gnu_mcount_nc捕获函数退出时间

c++ - 在插入或移除时获取 USB 的 dos_name

c++ - std::unordered_multimap 中元素的顺序