quant
quant

Reputation: 23082

How do I use regex_replace?

After asking this question on SO, I realised that I needed to replace all matches within a string with another string. In my case, I want to replace all occurrences of a whitespace with `\s*' (ie. any number of whitespaces will match).

So I devised the following:

#include <string>
#include <regex>

int main ()
{
  const std::string someString = "here is some text";
  const std::string output = std::regex_replace(someString.c_str(), std::regex("\\s+"), "\\s*");
}

This fails with the following output:

error: no matching function for call to ‘regex_replace(const char*, std::regex, const char [4])

Working example: http://ideone.com/yEpgXy

Not to be discouraged, I headed over to cplusplus.com and found that my attempt actually matches the first prototype of the regex_replace function quite well, so I was surprised the compiler couldn't run it (for your reference: http://www.cplusplus.com/reference/regex/match_replace/)

So I thought I'd just run the example they provided for the function:

// regex_replace example
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main ()
{
  std::string s ("there is a subsequence in the string\n");
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  // using string/c-string (3) version:
  std::cout << std::regex_replace (s,e,"sub-$2");

  // using range/c-string (6) version:
  std::string result;
  std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
  std::cout << result;

  // with flags:
  std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
  std::cout << std::endl;

  return 0;
}

But when I run this I get the exact same error!

Working example: http://ideone.com/yEpgXy

So either ideone.com or cplusplus.com are wrong. Rather than bang my head against the wall trying to diagnose the errors of those far wiser than me I'm going to spare my sanity and ask.

Upvotes: 8

Views: 10323

Answers (2)

bocz
bocz

Reputation: 11

Simple code C++ regex_replace only alphanumeric characters

#include <iostream>
#include <regex>
using namespace std;

int main() {
    const std::regex pattern("[^a-zA-Z0-9.-_]");
    std::string String = "!#[email protected]";
    // std::regex_constants::icase
    // Only first
    // std::string newtext = std::regex_replace( String, pattern, "X", std::regex_constants::format_first_only );
    // All case insensitive
    std::string newtext = std::regex_replace( String, pattern, "", std::regex_constants::icase);
    std::cout << newtext << std::endl;
    return 0;
}

Run https://ideone.com/CoMq3r

Upvotes: 1

deW1
deW1

Reputation: 5660

You need to update your compiler to GCC 4.9.

Try using boosts regex as an alternative

regex_replace

Upvotes: 8

Related Questions