How to validate identifier using Regular Expression in Java

Hello guys, in this tutorial we will learn how to validate an identifier using a regular expression in Java. A Regular Expression is an expression that represents a set of strings as per a specific pattern.
The main aim is to validate or check a given string whether it is a valid string or not using Regular expression.

To check the validity of a string, there are some rules in the regular expression to test on that given string –

  1. Given string should begin either with lower-case alplabet[a-z] or upper-case alphabet[A-Z] or a dollar sign($) or underscore(_).
  2. It must not begin with a numerical number/ digit[…-2,-1,0,1,2…].
  3. It must exclude white spaces in between.

Java program to validate identifier using Regular Expression

regex to create a valid identifier:

regex= "^([a-zA-Z_$][a-zA-Z\\d_$]*)$";

where,

  • ^: It alludes to the beginning character of a string.
  • [a-zA-Z_$]: It refers to the string start either with the lower case alphabet(a-z) or upper case alphabet(A-Z) or a dollar sign($) or underscore(_).
  • [a-zA-Z\\d_$]*: It refers back to the string that can be alphanumeric or dollar sign or underscore after the beginning character of the string.
  • $: It refers to the closure of a string.

 

Let’s understand this by an example,

import java.util.regex.*;
class Test{
  
   public static boolean checkValidity(String str){
    
    String regex="^([a-zA-Z_$][a-zA-Z\\d_$]*)$";

    Pattern p = Pattern.compile(regex); 
    
    if (str == null) { 
        return false; 
    }

    Matcher m = p.matcher(str); 
	return m.matches(); 
       
  }

  public static void main(String ar[]){
    String s1="code123";
    System.out.println(checkValidity(s1));
  
    String s2="232codespeedy";
    System.out.println(checkValidity(s2));
  }
}

output: 

true
false

 

Pattern:

A Pattern object refers to a compiled model of a Regular Expression. It compiles the regex by the usage of the compile() method to create a pattern.

Matcher:

A matcher is utilized to search through a content/string for multiple occurrences of a regular expression. matches() method returns true in the case, if the regex string fits the entire content/string str, else it returns false.

Leave a Reply

Your email address will not be published. Required fields are marked *