簡體   English   中英

如何使用帶有lambda函數的boost regex_replace?

[英]How to use boost regex_replace with a lambda function?

我正在嘗試使用lambda函數來調用std::string類型的boost::regex_replace 我沒有運氣讓所有類型都正確。

typedef boost::basic_regex<char> regex;
typedef boost::match_results<char> smatch;

    std::string text = "some {test} data";
    regex re( "\\{([^\\}]*)\\}" );
    text  = boost::regex_replace( text, re, [&](smatch const & what) {
        return what.str();
    });

我使用的是typedef而不是標准名稱,因為我有一些使用typedef / templated字符類型而不是固定類型的地方。

在這段代碼中我得到了這個錯誤: /usr/include/boost/regex/v4/match_results.hpp:68:77: error: no type named 'difference_type' in 'struct boost::re_detail::regex_iterator_traits<char>' BidiIterator>::difference_type difference_type;

正如match_results參考頁面上所記載boost::match_results的第一個類型參數是BidirectionalIterator類型; 所以,例如,標准的typedef boost::smatchmatch_results<std::string::const_iterator>

要修復代碼,你需要更正smatch的typedef,要么取消對拉姆達參數參考what或使之成為常量參考:

typedef boost::basic_regex<char> regex;
typedef boost::match_results<std::string::const_iterator> smatch;

std::string text = "some {test} data";
regex re("\\{([^\\}]*)\\}");
text = boost::regex_replace(text, re, [] (const smatch& what) {
    return what.str();
});

如果你有一個符合C ++ 11的編譯器,你既不需要Boost也不需要lambda。

要實現相同的目標,您只需使用std::regex

#include <iostream>
#include <regex>

int main()
{
  std::string text = "some {test} data {asdf} more";
  std::regex re("\\{([^\\}]*)\\}");
  std::string out;
  std::string::const_iterator it = text.cbegin(), end = text.cend();
  for (std::smatch match; std::regex_search(it, end, match, re); it = match[0].second)
  {
    out += match.prefix();
    out += match.str(); // replace here
  }
  out.append(it, end);
  std::cout << out << std::endl;
}

當然,對於簡單的文本替換,您可以使用std::regex_replace()但它不能接受仿函數,只能接受靜態格式字符串,可選擇使用組占位符:

  std::string text = "some {test} data {asdf} more";
  std::regex re("\\{([^\\}]*)\\}");
  std::string out = std::regex_replace(text, re, "<$1>");

smatch類型有問題。 我找不到一個帶有typename的工作示例,但使用C ++ 14 auto lambda參數解決了這個問題:

    auto text = "some {test} data";
    regex re( "\\{([^\\}]*)\\}" );
    text  = boost::regex_replace( text, re, [&](auto & what) {
        return what.str();
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM