Check alphabets and digits in String using RegEx

An example on checking whether a string contains only alphabets and numbers using Regular Expressions in Java.

Example



// For Pattern and Matcher

import java.util.regex.*;


// For Scanner

import java.util.*;


class CheckNumAlpha
{


public static void main(String args[])
{


// Create Scanner object

Scanner s=new Scanner(System.in);


// Read input from the user and store it in st

String st=s.nextLine();


// Create a regex pattern for alphabets (small & cap) and digits.

Pattern pattern=Pattern.compile("^[a-zA-Z0-9]$");


// Create a Matcher object for the compiled pattern [above]

Matcher m=pattern.matcher(st);


// Print whether the string contains only numbers and alphabets

System.out.println("Does it contain alphabets and numbers only (T/F)? "+m.matches());


}


}


Regular Expression Pattern


Starting of the regular expression.

Character class opening. 

Character class: A character class in regular expression is nothing but a set of characters that should be matched. A single character in the character class is matched each time and this is done till the end of the string. For example, foo contains f o o and for the above regular expression (in the program), first f is checked and next, o is checked and later o is checked as f o o lies between a-z the string foo is matched and satisfies the above regular expression.

a-z Match the alphabets from a till z

A-Z Match till A to Z. There is a difference between a-z and A-Z (the ASCII values)

0-9 Match all the digits from 0 till 9

] End of character class.

+ Match one or more characters (Match at least one). For a better understand, try giving Enter [Typing enter and nothing else] as input.

$ Ending of the regular expression.


Output


gowthamgutha
Does it contain alphabets and numbers only (T/F)? true

gowtham----gutha
Does it contain alphabets and numbers only (T/F)? false

--
Does it contain alphabets and numbers only (T/F)? false

gowthamgutha99
Does it contain alphabets and numbers only (T/F)? true


Does it contain alphabets and numbers only (T/F)? false

You'll have to note that the string that user gives need not contain all the alphabets and all the numbers instead it has to contain at least one alphabet (or) one number.

Note: For the last input, i just typed enter and it returned false, that is true of course. As said above [in the description of +] try keeping * instead of +, that will return true because * means that match at least 0 times.
You can also remove +, because that gives the same output. I've just said for explanation.

Also take time to see my other posts on Counting alphabets in String in Java and Counting no.of digits in String in Java

Feel free to drop a comment for further help.

No comments: