Checking strings with regex in C++

10,870

Solution 1

Seriously, regexp:s are not the right solution for you in this case.

To start with, regexp:s are not part of the C++ language so you will need to use a specific regexp library. (C++11, whoever, include support for regexp:s.)

Secondly, both your use cases can trivially be encoded in plain C++, all you need to do is to loop over the characters in the strings and check if each of them match your requirements.

Solution 2

X.anystring -> X must be necessarily and exclusively letter (not digit).

Required regex is

[a-zA-Z]\.[\w]+

XY.anystring -> X, Y must be necessarily and exclusively digits 0-9 (not letters).

Required regex is

[0-9]{2}\.[\w]+

Learn more about regexes here. Once you learn about regexes in general, you can apply to any language of your choice.

Solution 3

The current C++11 standard has support for regular expressions, though I'm not sure off the top of my head which compilers support it and are ready to go.

In the meanwhile, the Boost library provides a nice regular expression system for C++ (link here).

In terms of learning about regex, this may help (focuses on using the Boost regex).

An alternative solution that may be simpler for your case would to be just code it yourself. Something like:

bool check_first(const string& myString)
{
    if (!isalpha(myString[0]) || myString[1] != '.') return false;
    return true;
}

bool check_second(const string& myString)
{
    if (!isdigit(myString[0]) || !isdigit(myString[1]) || myString[2] != '.') return false;
    return true;
}

Solution 4

If you just want to know if a string matches one or the other, but you don't care which one it matches, you can use:

"(?:(?:[a-zA-Z])|(?:[0-9]{2}))\..*"

Using C++11 regex and ECMAScript syntax.

Solution 5

#include <regex>

std::string str = "OnlyLetter,12345";

std::string x = "([a-z]|[A-Z])+";
std::string y = "[0-9]+";
std::string expression = std::string(x).append(",").append(y);
std::tr1::regex rx(expression);
bool match = std::tr1::regex_match(str.c_str(),rx);
// match = true. Valid String
// match = false. Invalid String. ex.: "OnlyLetter,12s345"
Share:
10,870
arjacsoh
Author by

arjacsoh

Updated on June 28, 2022

Comments

  • arjacsoh
    arjacsoh almost 2 years

    I am going to use regular expressions in a C++ application, but I am not experienced in regex. I want in particular to check a number of strings if they belong to one of the following categories:

    X.anystring -> X must be necessarily and exclusively letter (not digit).

    XY.anystring -> X, Y must be necessarily and exclusively digits 0-9 (not letters).

    How can I check them using regex? What tutorial for regex could you recommend in order to acquaint me with regex?