How to check if a string contains only letters, numbers, underscores and dashes in C++

1 Answer

0 votes
#include <iostream>
#include <regex>

bool isValidString(const std::string& s) {
    std::regex pattern("^[A-Za-z0-9_-]*$");

    return std::regex_match(s, pattern);
}

int main() {
    std::string s1 = "-abc_123-";
    if (isValidString(s1)) {
        std::cout << "yes" << std::endl;
    } else {
        std::cout << "no" << std::endl;
    }

    std::string s2 = "-abc_123-(!)";
    if (isValidString(s2)) {
        std::cout << "yes" << std::endl;
    } else {
        std::cout << "no" << std::endl;
    }
}



/*
run:

yes
no

*/

 



answered May 31, 2025 by avibootz
...