10

I am using C++ 11's <regex> support, and would like to check whether the beginning of a string matches a regular expression. [I can switch to Boost if that helps, but my impression is that they're basically the same.]

Obviously if I have control of the actual textual representation of the expression, I can just stick a ^ at the beginning of it as an anchor.

However, what if I just have a regex (or basic_regex) object? Can I modify the regular expression it represents to add the anchor? Or do I have to use regex_search, get the result, and check whether it starts at position 0?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
EvanED
  • 947
  • 6
  • 22
  • Many ordinary string can be consider as regex. `"abc"` is also a regex, but only match the exact string. – nhahtdh Aug 08 '12 at 18:04

1 Answers1

12

You could add the std::regex_constants::match_continuous flag when using regex_search, for example, the following prints "1" and "0":

#include <regex>
#include <string>

int main()
{
    std::regex rx ("\\d+");

    printf("%d\n", std::regex_search("12345abc1234", rx,
                                     std::regex_constants::match_continuous));
    printf("%d\n", std::regex_search("abc12345", rx,
                                     std::regex_constants::match_continuous));
    return 0;
}

The flag means (C++11 §28.5.2/1 = Table 139):

The expression shall only match a sub-sequence that begins at first.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 4
    That's an, um, interesting name for the flag, but that's exactly what I wanted! Thanks a bundle – EvanED Aug 08 '12 at 21:59