C++ Pattern Matching

C++ pattern matching:

The following code example shows how to use regular expressions in C++ to see if a string is a valid name or not (names are 2-10 letters, no punctuation, no numbers):

#include <iostream>

#include <regex>

using namespace std;

int main() {

//name regex demo

//names are letters only

string this_matches = “Anthony”;

string does_not_match = “Barbara234”;

regex nameExp(“^[A-Za-z]{2,10}$”);

//above regex means 2-10 uppercase or lowercase characters

//with nothing else, as designated by ^ for the beginning

//and $ to indicate the end

cout << regex_match(this_matches, nameExp) << endl;

//above line displays 1, meaning it matches

cout << regex_match(does_not_match, nameExp) << endl;

//the above line displays 0, meaning it did not match

return 0;


← Previous | Next →

C++ Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *