#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char input[256]={0};
char regex[128]={0};
cout<<"input string/n";
cin>>input;
cout<<"input regex, no need for slash/n";
cin>>regex;
int reg_len=strlen(regex);
int input_len=strlen(input);
int start_anchor=(regex[0]=='^');
int end_anchor=(regex[reg_len-1]=='$');
cout<<"reglen "<<reg_len<<" start "<<start_anchor<<" end "<<end_anchor<<endl;
char * ip = input;
char * rp = regex;
if(start_anchor == 1)
{
rp ++ ; //jump over ^
while(*rp != '/0')
{
if(*rp == *ip)
{
ip++;
rp++;
continue;
}else
{
if(*rp == '.') //.matches any charactor
{
ip++;rp++;continue;
}else if (*rp == '*') // matches any number of previous charactor
{
if(*ip == *(rp-1))
{
//ip incr, rp do not change
ip++;
continue;
}else
{
rp ++;
}
}else if(*rp == '$')
{
if(ip-input == input_len) // last charactor of ip
{
cout<<"match with $!"<<endl;
return 0;
}
cout<<"not match end"<<endl;
return -1;
}else
{
cout <<"not match"<<endl;
return -1;
}
}//end of else
}
//reg to the end, output match
cout << "match!"<<endl;
return 0;
}else //not start with ^
{
while(*rp != '/0')
{
if(*ip == *rp)
{
ip++;rp++;continue;
}else
{
if(*rp == '.')
{
ip++;rp++;continue;
}else if (*rp == '*')
{
if(*ip == *(rp-1))
{
//ip incr, rp do not move
ip++;
continue;
}else
{
rp++;
continue;
}
}else if(*rp == '$')
{
if(ip - input == input_len) // last charactor of ip
{
cout<<"match with $!"<<endl;
return 0;
}else //behind can be match, so cant end matching, should turning back and match again.
{
rp = regex;
ip = ip - (reg_len -2);
}
}else
{
if (rp == regex)
ip++;
else
rp = regex;
}
}//end of else
if(ip-input == input_len)
{
cout << "come to end, not match!"<<endl;
return -1;
}
}//end of while
cout<<"match"<<endl;
return 0;
}
}