简体   繁体   中英

std::regex not working as expected

I googled around but still cannot find the error.

Why does the following code print false , I expected true ?

#include <iostream>
#include <regex>

using namespace std;

int main()
{
    std::string in("15\n");
    std::regex r("[1-9]+[0-9]*\\n",
                 std::regex_constants::extended);

    std::cout << std::boolalpha;
    std::cout << std::regex_match(in, r) << std::endl;
}

The option to use regex_search is not given.

There is an extra slash before the "\\n" in your regex. The code prints true with just the slash removed.

#include <iostream>
#include <regex>

using namespace std;

int main()
{
    std::string in("15\n");
    std::regex r("[1-9]+[0-9]*\n",
                 std::regex_constants::extended);

    std::cout << std::boolalpha;
    std::cout << std::regex_match(in, r) << std::endl;
}

Edit: @rici explains why this is an issue in a comment:

Posix-standard extended regular expressions (selected with std::regex_constants::extended ) do not recognize C-escape sequences such as \\n . See Posix base definitions 9.4.2 : "The interpretation of an ordinary character preceded by a ( '\\' ) is undefined."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM