Hi everyone!
Right now I'm working on a regular expression that searches for comparison operators (">", "<=", "!=", etc.).
Here's the regex I've come up with:
private static final String C = "[\\Q><!\\E]?\\=?"; //comparator regex
It looks for a ">", "<", or "!" once or not at all, followed by a "=" once or not at all. The "\\Q" starts a quote (because "<", ">", and "!" are reserved characters for regular expressions, I need to escape to use them) that is ended by the "\\E". The "\\" in front of the "=" is again an escape, because "=" is also a reserved regex character. All of these have two "\" because the compiler throws an illegal escape character otherwise; the first "\" lets it know that the second "\" should be taken literally.
So, I whipped that up, thought it would work, and was sorely disappointed...
I tested it using this simple code:
public static void main(String[] teehee) { String s = "> < >= <= = !="; Matcher m; for(String part : s.split(" ")) { m = Pattern.compile(C).matcher(part); //C being the regex I described above System.out.print("\'" + part + "\': "); if(m.find()) { System.out.println("Valid!"); } else { System.out.println("Invalid..."); } } }
Fortunately, when I ran that test, this was the result:
'>': Valid! '<': Valid! '>=': Valid! '<=': Valid! '=': Valid! '!=': Valid!
Unforunately, this regex gets so carried away that it accepts almost anything...
Changing the value of 's' to ">as fqq<f >fq= <f=Q =D !s=", this results:
'>as': Valid! 'fqq<f': Valid! '>fq=': Valid! '<f=Q': Valid! '=D': Valid! '!s=': Valid!
...what have I done wrong? I'd appreciate any help!