A regular expression is a set of pattern matching rules encoded in a string.Regular expression may match whole string or substring.
Here we will implement a regular expression matcher which will support . (dot), *, ^ and $.
Rules:
Rules:
. (dot) | Dot matches any single character |
* | Matches preceding character zero or more time |
bool regexMatch(string regex, string str)
{
if (regex.length() <= 0)
{
return true;
}
if (str.length() == 0 && regex.length() == 1 && regex[0] == '$')
{
return true;
}
if (str.length() > 0)
{
switch (regex[0])
{
case '^':
return regexMatch(regex.substr(1, regex.length() - 1), str);
case '.':
return regexMatch(regex.substr(1, regex.length() - 1), str.substr(1, str.length()-1));
case '*':
{
int itr = 0;
while (itr < str.size())
{
if (regexMatch(regex.substr(1, regex.length() - 1), str.substr(itr, str.length()-itr)))
{
return true;
}
itr++;
}
return false;
}
default:
{
int itr = 0;
while (itr < regex.size())
{
if (regex[itr] == str[itr])
{
itr++;
}
else if (regex[itr] == '.' || regex[itr] == '*' || regex[itr] == '$' || regex[itr] == '^')
return regexMatch(regex.substr(itr, regex.length() - itr), str.substr(itr, str.length()-itr));
else
return false;
}
return true;
}
return false;
}
}
return false;
}
|
No comments:
Post a Comment