0

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.

1 Answer 1

3

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."

Sign up to request clarification or add additional context in comments.

10 Comments

What is your compiler and platform? It prints true for me with gcc version 4.9.2 20141101 (Red Hat 4.9.2-1) (GCC) when I use the command g++ -std=c++11 r.cpp && ./a.out to compile and run the program.
It's okay, I used the wrong libc++ and thus obfuscated my regex. Thanks for help!
@NaCl - Shame on you !
@sln: 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 <backslash> ( '\\' ) is undefined."
@nhahtdh: It's more an explanation of why the accepted answer is correct; if nwk doesn't edit the answer, I might do so later. The important thing is that there is no such thing a universal regular expression syntax; every tool has its own syntax, and you need to take that into account rather than assuming that the syntax you are familiar with is applicable in context.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.