AR5HAM
AR5HAM

Reputation: 1304

Use regex to validate string not starting with specific character and string length

I have a function with the following if statements:

if (name.length() < 10 || name.length() > 64)
{
    return false;
}

if (name.front() == L'.' || name.front() == L' ')
{
    return false;
}

I was curious to see if can do this using the following regular expression:

^(?!\ |\.)([A-Za-z]{10,46}$)

to dissect the above expression the first part ^(?!\ |.) preforms a negative look ahead to assert that it is impossible for the string to start with space or dot(.) and the second part should take care of the string length condition. I wrote the following to test the expression out:

std::string randomStrings [] = {" hello", 
                                " hellllloooo", 
                                "\.hello", 
                                ".zoidbergvddd", 
                                "asdasdsadadasdasdasdadasdsad"};

std::regex txt_regex("^(?!\ |\.)([A-Za-z]{10,46}$)");

for (const auto& str : randomStrings)
{
    std::cout << str << ": " << std::boolalpha << std::regex_match(str, txt_regex) << '\n';
}

I expected the last one to to match since it does not start with space or dot(.) and it meets the length criteria. However, this is what I got:

 hello: false
 hellllloooo: false
.hello: false
.zoidbergvddd: false
asdasdsadadasdasdasdadasdsad: false

Did I miss something trivial here or this is not possible using regex? It seems like it should be.

Feel free to suggest a better title, I tried to be as descriptive as possible.

Upvotes: 1

Views: 210

Answers (2)

Change your regular expression to: "^(?![\\s.])([A-Za-z]{10,46}$)" and it will work.

\s refers to any whitespace and you need to escape the \ inside the string and that's why it becomes \\s.

You can also check this link

Upvotes: 1

Tim
Tim

Reputation: 1527

You need to turn on compiler warnings. It would have told you that you have an unknown escape sequence in your regex. I recommend using a raw literal.


#include <iostream>
#include <regex>

int main() {
    std::string randomStrings[] = { " hello", " hellllloooo", ".hello",
            ".zoidbergvddd", "asdasdsadadasdasdasdadasdsad" };

    std::regex txt_regex(R"foo(^(?!\ |\.)([A-Za-z]{10,46}$))foo");

    for (const auto& str : randomStrings) {
        std::cout << str << ": " << std::boolalpha
                  << std::regex_match(str, txt_regex) << '\n';
    }
}

clang++-3.8 gives

hello: false

hellllloooo: false

.hello: false

.zoidbergvddd: false

asdasdsadadasdasdasdadasdsad: true

Upvotes: 1

Related Questions