Saturday 1 November 2014

regular expression to validate java variable name

A variable's name can be any legal identifier, an unlimited-length sequence of letters and digits, $, _ and beginning with a letter, the dollar sign "$", or the underscore character "_".

1. A variable name must begin with a letter or $ or _.
[a-zA-Z$_]

2. After first character any letter, digit, $ or _ is valid.
[a-zA-Z0-9$_]*

Now the final regular expression is [a-zA-Z$_][a-zA-Z0-9$_]*
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);
                System.out.println(matcher.matches());               
            }
            catch(Exception e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output

Enter Regular Expression
[a-zA-Z$_][a-zA-Z0-9$_]*
Enter the string
abc
true
Enter the string
_123
true
Enter the string
abc$_123
true
Enter the string
123
false
Enter the string
12abc
false



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment