提问者:小点点

是否在C++11中用回调替换regex?


是否有一个regex替换函数将匹配项发送给用户函数,然后替换返回值:

我试过这个方法,但显然行不通:

cout << regex_replace("my values are 9, 19", regex("\d+"), my_callback);

和功能:

std::string my_callback(std::string &m) {
  int int_m = atoi(m.c_str());
  return std::to_string(int_m + 1);
}

结果应该是:我的值是10,20

我指的是类似于PHP的preg_replace_callback或Python的re.sub(模式,回调,主题)的工作模式

我指的是最新的4.9gcc,它能够在没有增强的情况下实现正则表达式。


共3个答案

匿名用户

我想要这种功能,不喜欢回答“使用Boost”。 本杰明回答的问题是它提供了所有的代币。 这意味着您不知道哪个令牌是匹配的,并且它不允许您使用捕获组。 这样做:

// clang++ -std=c++11 -stdlib=libc++ -o test test.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include <regex>

namespace std
{

template<class BidirIt, class Traits, class CharT, class UnaryFunction>
std::basic_string<CharT> regex_replace(BidirIt first, BidirIt last,
    const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
    std::basic_string<CharT> s;

    typename std::match_results<BidirIt>::difference_type
        positionOfLastMatch = 0;
    auto endOfLastMatch = first;

    auto callback = [&](const std::match_results<BidirIt>& match)
    {
        auto positionOfThisMatch = match.position(0);
        auto diff = positionOfThisMatch - positionOfLastMatch;

        auto startOfThisMatch = endOfLastMatch;
        std::advance(startOfThisMatch, diff);

        s.append(endOfLastMatch, startOfThisMatch);
        s.append(f(match));

        auto lengthOfMatch = match.length(0);

        positionOfLastMatch = positionOfThisMatch + lengthOfMatch;

        endOfLastMatch = startOfThisMatch;
        std::advance(endOfLastMatch, lengthOfMatch);
    };

    std::regex_iterator<BidirIt> begin(first, last, re), end;
    std::for_each(begin, end, callback);

    s.append(endOfLastMatch, last);

    return s;
}

template<class Traits, class CharT, class UnaryFunction>
std::string regex_replace(const std::string& s,
    const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
    return regex_replace(s.cbegin(), s.cend(), re, f);
}

} // namespace std

using namespace std;

std::string my_callback(const std::smatch& m) {
  int int_m = atoi(m.str(0).c_str());
  return std::to_string(int_m + 1);
}

int main(int argc, char *argv[])
{
    cout << regex_replace("my values are 9, 19", regex("\\d+"),
        my_callback) << endl;

    cout << regex_replace("my values are 9, 19", regex("\\d+"),
        [](const std::smatch& m){
            int int_m = atoi(m.str(0).c_str());
            return std::to_string(int_m + 1);
        }
    ) << endl;

    return 0;
}

匿名用户

您可以使用regex_token_iterator

#include <iostream>
#include <algorithm>
#include <regex>
#include <string>
#include <sstream>

int main()
{
    std::string input_text = "my values are 9, 19";
    std::string output_text;
    auto callback = [&](std::string const& m){
        std::istringstream iss(m);
        int n;
        if(iss >> n)
        {
            output_text += std::to_string(n+1);
        }
        else
        {
            output_text += m;
        }
    };

    std::regex re("\\d+");
    std::sregex_token_iterator
        begin(input_text.begin(), input_text.end(), re, {-1,0}),
        end;
    std::for_each(begin,end,callback);

    std::cout << output_text;
}

注意,迭代器构造函数的参数列表中的{-1,0}是一个指定我们要迭代的子匹配的列表。 -1用于不匹配的部分,0用于第一个子匹配。

还要注意,我没有广泛使用过C++11正则表达式功能,也不是这方面的专家。 所以这个代码可能有问题。 但是对于您的特定输入,我对其进行了测试,它似乎产生了预期的结果。 如果您发现任何输入集,它不工作,请让我知道。

匿名用户

也许我来这个派对太晚了(大概5年),但我不喜欢答案“使用增强”,下面的函数有较少的泛化(说到字符串类型),但显然工作。 但是,我不知道使用std::oStringStream是否比std::string::append:

std::string regex_replace(
    const std::string& input,
    const std::regex& regex, 
    std::function<std::string(std::smatch const& match)> format) {

    std::ostringstream output;
    std::sregex_iterator begin(input.begin(), input.end(), regex), end;
    for(; begin != end; begin++){
        output << begin->prefix() << format(*begin);
    }
    output << input.substr(input.size() - begin->position());
    return output.str();
}

因此,如您所见,我使用了std::sregex_iterator而不是std::sregex_token_iterator

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++11|中|用回|调|替换|regex)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?