Sunday, June 10, 2018

Regular Expression in C++

RegexDemo.h:


#ifndef REGEXDEMO_H
#define REGEXDEMO_H

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

class RegexDemo
{
    public:
        /** Default constructor */
        RegexDemo(char const *str) : m_str(str), m_matches() {};
        RegexDemo(std::string const & str);
        /** Default destructor */
        virtual ~RegexDemo();

        bool match(std::string const & pattern)
        {
            return match(pattern.c_str());
        }
        bool match(char const * pattern);

        std::cmatch& get_cmatch() { return m_matches; }

        friend std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm);
    protected:

    private:
        std::string     m_str;
        std::cmatch     m_matches;
        std::regex_constants::match_flag_type flag = std::regex_constants::match_any;
};


std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm);

#endif // REGEXDEMO_H


RegexDemo.cpp:


#include "RegexDemo.h"

RegexDemo::RegexDemo(std::string const & str) :
    m_str(str), m_matches()
{
    //ctor
}

RegexDemo::~RegexDemo()
{
    //dtor
}


#if 0
bool RegexDemo::match(std::string const & pattern)
{
    std::regex exp(pattern);
    return std::regex_match(m_str, exp);
}
#endif


bool RegexDemo::match(char const * pattern/*, std::cmatch &cm*/)
{
    std::regex exp(pattern);
    return std::regex_match(m_str.c_str(), m_matches, exp, flag);
}


std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm)
{
    for(unsigned i=0; i< cm.size(); ++i)
    {
        ios << "[" << cm[i] << "] ";
    }

    return ios;
}


main.cpp:

#include <iostream>
#include "RegexDemo.h"

using namespace std;

int main()
{
    RegexDemo reg("Hello, World Ahsan,123Bae!");

    std::cout << "Match1: " << reg.match(".*123!") << std::endl;

    std::cmatch matches;
    if (reg.match("(.*),([0-9]+)(.*)"))
    {
        std::cout << "The matches were: " << reg.get_cmatch() << std::endl;
        std::cout << "The number is " << reg.get_cmatch()[2] << std::endl;
    }
    return 0;
}

The Output


$ ./myregex 
Match1: 0
The matches were: [Hello, World Ahsan,123Bae!] [Hello, World Ahsan] [123] [Bae!] 
The number is 123