Search code examples
c++re2

Escape string using RE2::GlobalReplace


Due to reasons, I am only using RE2 for regex matching in the project.

I am trying to escape specific characters using RE2 library.

std::string aInput = "~/Test (Folder)/";
RE2::GlobalReplace( &aInput, "(<|>|\\||\\:|\\(|\\)|&|;|\\s)", "\\\\0" );

I know that \0 is inserting whole matching group but once I am adding an escape symbol I am receiving unexpected result:

~/Test\0\0Folder\0

instead of

~/Test\ \(Folder\)/

How to insert \ before each matching group using RE2?

PS. RE2::QuoteMeta() is not an option for me as it will escape characters I don't need to be escaped.


Solution

  • Regular expression groups begin with 1, not 0. Besides that you use "\\\\0" as the replacement string. This is a literal "\0" in your final regex. Replace "\\\\0" with "\\\\\\1". This will evaluate to "\\\1", which is a literal \ and the first matching group.

    You can design and test regular expressions and the state machines they generate with this helpful site