C++ Anchors


Example

C++ provides only 4 anchors:

  • ^ which asserts the start of the string
  • $ which asserts the end of the string
  • \b which asserts a \W character or the beginning or end of the string
  • \B which asserts a \w character

Let's say for example we want to capture a number with it's sign:

auto input = "+1--12*123/+1234"s;
smatch sm;

if(regex_search(input, sm, regex{ "(?:^|\\b\\W)([+-]?\\d+)" })) {

    do {
        cout << sm[1] << endl;
        input = sm.suffix().str();
    } while(regex_search(input, sm, regex{ "(?:^\\W|\\b\\W)([+-]?\\d+)" }));
}

Live Example

An important note here is that the anchor does not consume any characters.