std::regex, to match begin/end of string

前端 未结 4 1358
误落风尘
误落风尘 2020-12-31 05:46

In JS regular expressions symbols ^ and $ designate start and end of the string. And only with /m modifier (multiline

4条回答
  •  粉色の甜心
    2020-12-31 06:39

    By default, ECMAscript mode already treats ^ as both beginning-of-input and beginning-of-line, and $ as both end-of-input and end-of-line. There is no way to make them match only beginning or end-of-input, but it is possible to make them match only beginning or end-of-line:

    When invoking std::regex_match, std::regex_search, or std::regex_replace, there is an argument of type std::regex_constants::match_flag_type that defaults to std::regex_constants::match_default.

    • To specify that ^ matches only beginning-of-line, specify std::regex_constants::match_not_bol
    • To specify that $ matches only end-of-line, specify std::regex_constants::match_not_eol
    • As these values are bitflags, to specify both, simply bitwise-or them together (std::regex_constants::match_not_bol | std::regex_constants::match_not_eol)
    • Note that beginning-of-input can be implied without using ^ and regardless of the presence of std::regex_constants::match_not_bol by specifying std::regex_constants::match_continuous

    This is explained well in the ECMAScript grammar documentation on cppreference.com, which I highly recommend over cplusplus.com in general.

    Caveat: I've tested with MSVC, Clang + libc++, and Clang + libstdc++, and only MSVC has the correct behavior at present.

提交回复
热议问题