How to validate identifier using Regular Expression in Java
- It must start with either lower case alphabet[a-z] or upper case alphabet[A-Z] or underscore(_) or a dollar sign($).
- It should be a single word, the white spaces are not allowed.
- It should not start with digits.
Input: str = “$geeks123”
Explanation: The given string satisfies all the above mentioned conditions.
Input: str = “$gee ks123”
Explanation: The given string contains white spaces, therefore it is not a valid identifier.
Input: str = “1geeks$”
Explanation: The given string start with digit, therefore it is not a valid identifier.
Approach: This problem can be solved by using Regular Expression.
- Get the string.
- Create a regex to check the valid identifiers.
regex = "^([a-zA-Z_$][a-zA-Z\\d_$]*)$";
- ^ represents the starting character of the string.
- [a-zA-Z_$] represents, the string start with only lower case alphabet or upper case alphabet or underscore(_) or dollar sign($).>/li>
- [a-zA-Z\\d_$]* represents, the string can be alphanumeric or uderscore(_) or dollar sign($) after the first character of the string. It contains one or more time.
- $ represents the ending of the string.
4. Match the given string with the Regex. In Java, this can be done using Pattern.matcher().
5. Return true if the string matches with the given regex, else return false.
Below is the implementation of the above approach:
true false false
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.