Search code examples
c++regexre2

re2 doesn't change string at all


I made this code right here on my first try with re2:

string s;
RE2::PartialMatch(".+\\.com","http://example.com/", &s);

It doesn't work; s doesn't change and remains blank. I could change that first line to string s = "foo"; and after the second line runs, s would stay as "foo".

What am I doing wrong?


Solution

  • There are two things wrong with your usage of PartialMatch:

    1. As already mentioned by Jesse Good, the regex should be the second argument not the first.
    2. The pointer arguments to PartialMatch are used to store the substrings matched by the capturing groups of the regular expression. Your regular expression doesn't contain any capturing groups, so nothing is written to the pointer.

    This should work:

    RE2::PartialMatch("http://example.com/", "(.+\\.com)", &s);
    

    Or if you don't want s to include the ".com" part:

    RE2::PartialMatch("http://example.com/", "(.+)\\.com", &s);