Ashif
Ashif

Reputation: 1684

How to Validate string Expression using RegExp?

I have a string "\03COUNTER\TIME_NOW"

Valid Range of min to Max allowed for COUNTER prefix is 01 to 09

Example:

"\02COUNTER\TIME_NOW": Valid

"\10COUNTER\TIME_NOW": Not valid

"\00COUNTER\TIME_NOW": Not valid

"\88COUNTER\TIME_NOW": Not valid

Can some one give how to get state of valid/Not valid using regexpression?

Upvotes: 0

Views: 62

Answers (1)

user1
user1

Reputation: 4131

\\0[1-9]COUNTER\\TIME_NOW is the regex you are looking for.

#include <iostream>
#include <string>
#include <regex>

int main ()
{
    if (std::regex_match ("\\02COUNTER\\TIME_NOW", std::regex("\\\\0[1-9]COUNTER\\\\TIME_NOW") ))
        std::cout << "valid\n";
    else
        std::cout << "invalid\n";

    if (std::regex_match ("\\10COUNTER\\TIME_NOW", std::regex("\\\\0[1-9]COUNTER\\\\TIME_NOW") ))
        std::cout << "valid\n";
    else
        std::cout << "invalid\n";

    if (std::regex_match ("\\00COUNTER\\TIME_NOW", std::regex("\\\\0[1-9]COUNTER\\\\TIME_NOW") ))
        std::cout << "valid\n";
    else
        std::cout << "invalid\n";

    if (std::regex_match ("\\88COUNTER\\TIME_NOW", std::regex("\\\\0[1-9]COUNTER\\\\TIME_NOW") ))
        std::cout << "valid\n";
    else
        std::cout << "invalid\n";

    return 0;
}

prints

valid
invalid
invalid
invalid

Upvotes: 1

Related Questions