1

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

  • % dipp 参加 --> 参加
  • aprè s. 专业知识 --> 四月,专业知识
  • ncpc condamner --> condamner

我正在尝试以下代码:

#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 个字符串

4

1 回答 1

1

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

这样做的唯一方法似乎是 via 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。你的代码甚至不应该编译。
  • 我在您的(第一个,这是正确的!)正则表达式周围添加了括号,以便它为每个匹配项创建一个捕获。然后迭代器依次迭代每个匹配项。
于 2013-06-27T16:11:37.360 回答