Cesar
Cesar

Reputation: 389

\K operator does not work in std::regex_replace regex

The value of name is: regex101: build, test, and debug regex - 3 running windows im trying to remove everything forward the last -

std::wstring name = accvector[i].name;
std::wregex regexp(L".*\\K( -\\s+\\d+\\srunning.*$)");
name = std::regex_replace(name, regexp, L"");

nothing is being replace, whats wrong?

Upvotes: 1

Views: 151

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You should keep in mind that \K operator is not supported by ECMAScript regex flavor (used by default in std::wregex/std::regex). It is mainly supported by PCRE, Boost, Onigmo, Python PyPi regex library.

Here, you may use

(.*) -\s+\d+\srunning.*

The replacement pattern should be $1.

See the C++ demo:

#include <iostream>
#include <regex>

int main()
{
    std::wstring name = L"regex101: build, test, and debug regex - 3 running windows";
    std::wregex regexp(LR"((.*) -\s+\d+\srunning.*)");
    name = std::regex_replace(name, regexp, L"$1");
    std::wcout << name;
}

Output:

enter image description here

Note you do not need the $ at the end of the pattern, .* matches till the end of the line/string.

Upvotes: 1

Related Questions