I want to learn how to use regular expressions in Java and found the following tasks: Write a class to check whetever a given input string is a valid arithmetic term based on these criteria in BNF-form:
term = [Vz]summand|[Vz]summand addOp term
summand = factor | factor mulOp summand
factor = number | '('term')'
number = digit | digit number
digit = '0'|'1'|...|'9'
vz = '+'|'-'
addOp = '+'|'-'
mulOp = '*'|'/'
Using these rules, I wrote some patterns, resembling the different types:
static Pattern vz = Pattern.compile("[+-]");
static Pattern addOp = Pattern.compile("[+-]");
static Pattern multOp = Pattern.compile("[*/]");
static Pattern digit= Pattern.compile("[0-9]");
static Pattern number = Pattern.compile(digit.pattern()+"+");
static Pattern factor = Pattern.compile(number.pattern()+"|("+term.pattern()+")");
static Pattern summand = Pattern.compile(factor.pattern()+"|"+factor.pattern()+ multOp.pattern()+"\n");
static Pattern term = Pattern.compile(vz.pattern()+"?"+summand.pattern()+"|"
+vz.pattern()+"?"+summand.pattern()+addOp.pattern()+"\n");
And you already see my problem: I reference term in the definiton of factor without having it defined first. Unfortunately I can not switch it around in any way. So my question is:
Is there a possibility to reference a pattern in such a way? Or any other to reference a pattern and defining it later on?