1

I am pass the following string to a function as so

void func(string expr)
{ 
    regex pattern(expr);
}

func( "(\d{1,2}\.+\d{2})" )

however through the visual studio debugger I have found that the regex pattern being stored is actually (d{1,2}.+d{2}) which is causing my regex to malfunction entirely. Why is this happening and how can I fix it.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Risen
  • 61
  • 5
  • 2
    Handy reading: [Escape character](https://en.wikipedia.org/wiki/Escape_character) – user4581301 Nov 16 '19 at 19:49
  • 1
    C/C++ ["string literal"](https://learn.microsoft.com/en-us/cpp/c-language/c-string-literals?view=vs-2019) treat the backslash ("\") as ["escapes"](https://learn.microsoft.com/en-us/cpp/c-language/escape-sequences?view=vs-2019). SOLUTION: `func( "(\\d{1,2}\\.+\\d{2})" )`. This will "escape" the "escape metacharacter". Alternatively, in C#, you can use [@](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim) – paulsm4 Nov 16 '19 at 19:49
  • 1
    That link is for c#, not c++. @Pete-Becker – Scott Hutchinson Nov 16 '19 at 19:52
  • 2
    What about `R"[(\d{1,2}\.+\d{2})]"` ? Can that be done in C#? No. That link is not discoverable, because it does not have a C++ tag. And don't call people names. – Scott Hutchinson Nov 16 '19 at 20:06
  • 1
    @ScottHutchinson -- good point. Reopened. Apparently I can't vote to close it again, so someone else will have to do that with a more appropriate link. – Pete Becker Nov 16 '19 at 20:17
  • Does this answer your question? [Why must backslashes in string literals be escaped in C++?](https://stackoverflow.com/questions/13986708/why-must-backslashes-in-string-literals-be-escaped-in-c) – Raymond Chen Nov 17 '19 at 00:30

1 Answers1

1

Those are backslashes, which by default are escape characters. To treat them as literal characters...

Try this (in C++11). The R indicates a raw string, which takes the form R "delimiter( raw_characters )delimiter", where delimiter can be any sequence of characters you like. In this case, I used just parentheses.

func( R"((\d{1,2}\.+\d{2}))" )

or this in any version:

func( "(\\d{1,2}\\.+\\d{2})" )
Scott Hutchinson
  • 1,703
  • 12
  • 22