I want to match alphanumeric words separated by the operators, +, -, *, /, <, > and ending with a semicolon. There can be whitespace characters in between e.g. the following strings should return true:
first + second;
first - second;
first * second;
first / second;
first;
first + second < third;
third < second * first;
This is what I have tried:
public boolean isExpr(String line) {
// factor = ([A-Za-Z]+|[0-9]+) for example: aasdaa or 23131 or xyz or 1 or a
// simple-expr = (factor {mulop factor} {addop factor {mulop factor}})
// expr = simple-expr compop simple-expr | simple-expr
String factor = new String("([A-Za-Z]+|[0-9]+)");
String mulOp = new String("(\\*|\\/)"); // '*'' or '/'
String addOp = new String("(\\+|\\-)"); // '+' or '-'
String compOp = new String("(\\<|\\="); // '<' or '='
String simpleExpr = new String("(" + factor + " (" + mulOp + " " + factor + ")? (" + addOp + " " + factor + " (" + mulOp + " " + factor + ")?)?");
String expr = new String("(" + simpleExpr + " " + compOp + " " + simpleExpr + ")|" + simpleExpr);
System.out.println(line.matches(expr));
return line.matches(expr);
}
What is wrong with that code and how can I solve it?
I got the below error on executing my code:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 9
((([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-Z]+|[0-9]+))? ((\+|\-) ([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-Z]+|[0-9]+))?)? (\<|\= (([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-eZ]+|[0-9]+))? ((\+|\-) ([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-Z]+|[0-9]+))?)?)|(([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-Z]+|[0
-9]+))? ((\+|\-) ([A-Za-Z]+|[0-9]+) ((\*|\/) ([A-Za-Z]+|[0-9]+))?)?
A-Za-Zshould beA-Za-znew String"([A-Za-z]+|[0-9]+)")makes no sense at all,"([A-Za-z]+|[0-9]+)"already is a string, you don't need create a new one, and doing so is a waste of time and memory. The same goes for all you other uses ofnew String(...). The only constructor of String you should ever need to call is one that takes a byte array and a character set.