Last active
March 18, 2019 23:17
-
-
Save dkohlsdorf/0a577131422e24d546e6 to your computer and use it in GitHub Desktop.
Parse A Regular Expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package parser; | |
public class ExpressionNode { | |
public static final char or = '|'; | |
public static final char and = '.'; | |
public static final char repeat = '*'; | |
public char symbol; | |
public ExpressionNode left, right; | |
public static boolean parse(String string, ExpressionNode expression) { | |
if (expression.symbol == or) { | |
boolean result = false; | |
for (int i = 0; i < string.length() + 1; i++) { | |
result |= parse(string, expression.left) | |
|| parse(string, expression.right); | |
} | |
return result; | |
} else if (expression.symbol == and) { | |
boolean result = false; | |
for (int i = 0; i < string.length() + 1; i++) { | |
result |= parse(string.substring(0, i), expression.left) | |
&& parse(string.substring(i, string.length()), | |
expression.right); | |
} | |
return result; | |
} else if (expression.symbol == repeat) { | |
if (string.length() > 0) { | |
int match = -1; | |
for (int i = 0; i < string.length() + 1; i++) { | |
if (parse(string.substring(0, i), expression.left)) { | |
match = i; | |
} | |
} | |
if(match < 0) { | |
return false; | |
} | |
return parse(string.substring(match, string.length()),expression); | |
} | |
return true; | |
} else { | |
return string.length() == 1 && string.charAt(0) == expression.symbol; | |
} | |
} | |
public static void main(String[] args) { | |
ExpressionNode a = new ExpressionNode(); | |
a.symbol = 'a'; | |
ExpressionNode b = new ExpressionNode(); | |
b.symbol = 'b'; | |
ExpressionNode ab = new ExpressionNode(); | |
ab.symbol = ExpressionNode.and; | |
ab.left = a; | |
ab.right = b; | |
System.out.println(parse("ab", ab)); | |
System.out.println(parse("acb", ab)); | |
System.out.println(parse("abb", ab)); | |
System.out.println(parse("a", ab)); | |
System.out.println(parse("b", ab)); | |
ExpressionNode abn = new ExpressionNode(); | |
abn.symbol = ExpressionNode.repeat; | |
abn.left = ab; | |
System.out.println(parse("ab", abn)); | |
System.out.println(parse("abc", abn)); | |
System.out.println(parse("abab", abn)); | |
System.out.println(parse("ababab", abn)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment