I need to build some kind of "java syntax" compiler in university. I want to use regex to match variable type and variable name (int num , String str etc.). So I need the regex to match one of the var types (String, int, char, boolean, double) and after that at least one space and var name, but var name CAN NOT be one of those types. How do I do that? I tried:
(String|int|char|boolean|double)[\s]+([a-zA-Z]+[\w]*^(String|int|char|boolean|double))
I know its not java regex syntax (only one '\' instead of two), but I tried this in http://regexpal.com/ and it doesn't work.
Thanks a lot!
A Negative Lookahead
^ will not work where you have it (it is an anchor that tries to assert that we are at the beginning of the string). But you were close, and if you just add ?! at the beginning of ethe parentheses that follow, it turns into a negative lookahead:
(String|int|char|boolean|double)\s+(?!(?:String|int|char|boolean|double)\b)[a-zA-Z]+
See demo
\s and \w (unneeded).(?!(?:String|int|char|boolean|double)\b) asserts that what follows is not one of your types. If the assertion succeeds, the engine proceeds to match your var, specified by [a-zA-Z]+Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With