C++ 11 regex: checking if string starts with regex
Asked Answered
G

1

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?

Galsworthy answered 8/8, 2012 at 18:1 Comment(1)
Many ordinary string can be consider as regex. "abc" is also a regex, but only match the exact string.Naturalize
D
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.

Dorree answered 8/8, 2012 at 18:20 Comment(1)
That's an, um, interesting name for the flag, but that's exactly what I wanted! Thanks a bundleGalsworthy

© 2022 - 2024 — McMap. All rights reserved.