1

LIVE

#include <iostream>
#include <regex>

int main()
{
    std::string text = R"(11111111111111111111
11111111111111111111
11111111111111111111
11111111111110000000
11111111111000000000
11111111100011111100
11111111100111100000)";

    std::regex re("^1+\n");
    std::string str = std::regex_replace(text, re, "");
    std::cout << str;
  return 0;
}

Why does the exact same code when compiled under visual studio, trims all lines containing 11111111111111111111?

I would like to it behave the same as on the link above, replacing just the first occurrence.

Do i need any kind of 'special' flag into the regex?

Cesar
  • 41
  • 2
  • 5
  • 16

1 Answers1

1

I modified my answer. It might be a compiler difference. You can refer to the flags and similar thread.

std::regex_constants::match_flag_type fonly =
    std::regex_constants::format_first_only;
std::regex re("^1+\n");
std::string str = std::regex_replace(text, re, "", fonly);
Minxin Yu - MSFT
  • 2,234
  • 1
  • 3
  • 14
  • When should i use this flag? – Cesar Sep 07 '22 at 03:01
  • So can i assume that this flag set `regex_replace` to replace only the `first` occurence?https://stackoverflow.com/questions/33105581/stdregex-replace-only-first-occurence – Cesar Sep 07 '22 at 03:19
  • To begin, why does the regex match things in multiple lines? By default std::regex lib matches things multi-line? – Cesar Sep 07 '22 at 03:40
  • [MSDN document](https://learn.microsoft.com/en-us/cpp/standard-library/regex-constants-class?view=msvc-170#match_flag_type)`format_first_only -- do not search for matches after the first one.` . Looks like regex matches multiple lines by default. – Minxin Yu - MSFT Sep 07 '22 at 05:25
  • E.g. The description of the document `regex_match`: Tests whether a regular expression matches the **entire target string**. – Minxin Yu - MSFT Sep 07 '22 at 05:34