get rid of extra whitespaces when performing std::regex_replace

Viewed 45

How to get rid of extra whitespaces when performing std::regex_replace using back references.

#include <iostream>
#include <regex>

int main() {
    const std::string str { "https://www.youtube.com\t"
    "http://www.google.com"
    };

    const std::regex reg_pattern { R"((https?://([\w\.?]+)([\s]*)))" };
    std::string res;
    std::regex_replace(std::back_inserter(res), std::begin(str), std::end(str), reg_pattern, "<a href='$1'>$2</a>\n");
    std::cout << res << std::endl;
}

This is the output I'm getting

<a href='https://www.youtube.com    '>www.youtube.com</a>
<a href='http://www.google.com'>www.google.com</a>

I'm trying to get the following output

<a href='https://www.youtube.com'>www.youtube.com</a>
<a href='http://www.google.com'>www.google.com</a>
1 Answers

You can use

(https?://(\S+))\s*

See the regex demo. Details:

  • (https?://(\S+)) - Group 1: https:// or http:// and then one or more non-whitespace chars captured into Group 2
  • \s* - zero or more whitespaces.

See the C++ demo:

#include <iostream>
#include <regex>

int main() {
    const std::string str { "https://www.youtube.com\t"
    "http://www.google.com"
    };

    const std::regex reg_pattern { R"((https?://(\S+))\s*)" };
    std::string res;
    std::regex_replace(std::back_inserter(res), std::begin(str), std::end(str), reg_pattern, "<a href='$1'>$2</a>\n");
    std::cout << res << std::endl;
}

Output:

<a href='https://www.youtube.com'>www.youtube.com</a>
<a href='http://www.google.com'>www.google.com</a>
Related