Given a string str , the task is to check whether the string is a valid identifier or not using the Regular Expression . The valid rules for defining Java identifiers are:
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.
Examples:
Input: str = “$geeks123” Output: True Explanation: The given string satisfies all the above mentioned conditions.Input: str = “$gee ks123” Output: False Explanation: The given string contains white spaces, therefore it is not a valid identifier.Input: str = “1geeks$” Output: False 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_$]*)$";
3. where:
^ 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 underscore(_) 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:
Java
import java.util.regex.*;
class GFG {
public static boolean
isValidIdentifier(String identifier)
{
String regex = "^([a-zA-Z_$][a-zA-Z\\d_$]*)$";
Pattern p = Pattern.compile(regex);
if (identifier == null) {
return false;
}
Matcher m = p.matcher(identifier);
return m.matches();
}
public static void main(String args[])
{
String str1 = "$geeks123";
System.out.println(isValidIdentifier(str1));
String str2 = "$gee ks123";
System.out.println(isValidIdentifier(str2));
String str3 = "1geeks$";
System.out.println(isValidIdentifier(str3));
}
}
Time complexity : O(1)
Space complexity : O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
31 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...