3

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!

2 Answers 2

3

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

  • Removed the brackets around \s and \w (unneeded).
  • The negative lookbehind (?!(?: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]+
  • For more on lookarounds, see the reference section.

Reference

Sign up to request clarification or add additional context in comments.

9 Comments

FYI fixed a small bug, added demo. Let me know if you have questions. :)
You're welcome, glad to hear it! Since it works, could you please click on the checkmark to the left of the answer to mark that you accept it? This is how the rep system works, accepting answers earns reputation both for the answerer and for you. Cheers!
Sure, no problem. But I found out it's not working as good as I thought - because for example "int intro" should work, and in your solution it's not. I mean I need it to accept averything except the actual string "int".
Sorry, Im new to this site, could you please send me the link to the other question? I'll gladly accept it. thanks again.
Btw on that question I have no idea if the answer was right for you. Just nice to hear some feedback. :) Give me a moment.
|
0

An answer which I think works for all cases..

public static void main(String[] args) {
    String s = "String String1";
    System.out.println(s.matches("(?!((String|double)\\s+(String|double|\\d+|$)$))(.*)"));
} 

O/P :
String s = "String String1";
answer : true

String s = "String String";
answer : false

String s = "String 123";
answer : false

String s = "String ";
answer : false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.