2

I didn't found any algorithms or regular expression or libraries in google for checking given String is a valid Java Identifier or not. I know the rules of valid declaration for java identifier (or may be help with IDE).

Can somebody support me How to check valid java identifer ?

PS : please don't be request to describe my efforded codes because I am not too familiar with regular expressions and I know I can write with hard-codes by myself. I am finding better and easy way to check it.

9
  • 1
    First result on google : stackoverflow.com/questions/5205339/… Commented Mar 20, 2015 at 10:21
  • 2
    You can check here : Check whether the given String is a valid identifier according to the Java Language specifications. Commented Mar 20, 2015 at 10:23
  • @Patrick OP wants to check if string can be used as reference name, not necessary as a type. Commented Mar 20, 2015 at 10:24
  • 1
    @Cataclysm No these rules are different, for instance references can't contain . in it while . is valid part of type name since it describes its package structure. Commented Mar 20, 2015 at 10:26
  • 1
    BTW after validating if structure of your string is valid to be variable name you will need to check if it is not Java reserved keyword. Commented Mar 20, 2015 at 10:31

1 Answer 1

0

I think you should try this

public class IdentifierTest { /** * @param args the command line arguments */ public static void main(String[] args) { for(String arg : args) { boolean start = true; boolean validIdentifier = true; arg.toCharArray() // commenter pointed out my error //for(byte b : arg.getBytes()) { for(char b : arg.toCharArray()) { if(start) { validIdentifier = validIdentifier && Character.isJavaIdentifierStart(b); start = false; } else { validIdentifier = validIdentifier && Character.isJavaIdentifierPart(b); } } System.out.println("Identifier \"" + arg + "\" is " + (validIdentifier ? "" : "not ") + "valid"); } } 

}

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

1 Comment

What about java keyword?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.