Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Created November 15, 2012 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheSavior/4082450 to your computer and use it in GitHub Desktop.
Save TheSavior/4082450 to your computer and use it in GitHub Desktop.
Simple Regex Parsing
/*Implement a function which answers whether a given string matches a provided pattern. The pattern is written in a small regex-like language, consisting of:
- Lowercase latin characters (a to z)
- . (dot), which matches any latin character.
- *, indicates that the previous character is repeated 0 or more times.
- +, indicates that the previous character is repeated 1 or more times.
You can assume that the input pattern is well formed and the string to match consists of lowercase latin characters only.
Examples:
match('abba', 'abba') == true
match('cda', 'adb) == false
match('.*abc', 'abc') == true
match('.*abc', 'ababc') == true
match('.b*ac*aa+', 'caaa') == true
match('bb+a*', 'baa') == false
match('.*abc.*a*b*', 'ababc') == true
'.*abc' -> ['.*', 'a', 'b', 'c']
*/
public bool match(string regex, string input) {
string newRegex = "";
for (int i = 0; i < regex.length; i++) {
if (regex[i] == "+") {
newRegex+= regex[i-1]+"*";
}
else
{
newRegex+=regex[i];
}
}
return rHelper(newRegex, input);
}
public bool rHelper(string regex, string input) {
if (input == "") {
for (int i = regex.length -1; i >= 0; i--) {
if (regex[i] == "*") {
i--;
}
else
{
return false;
}
}
return true;
}
if (regex[0] == input[0] || regex[0] == ".") {
if (regex.length > 1 && regex[1] == "*") { // possible bug (in case where regex.length == 1)
bool r1 = rHelper(regex, input.substring(1));
bool r2 = rHelper(regex.substring(2), input);
return r1 || r2;
}
else
{
return rHelper(regex.substring(1), input.substring(1));
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment