regular expressions in java

Java provides the java.util.regex package for pattern matching with regular expressions.
regular expressions can be used to search, edit, or manipulate text and data.

java.util.regex consist of following classes : 

  • Pattern
  • Matcher
  • PatternSyntaxException
  1. Pattern : It is used to define pattern or input we need from user.pattern class is not provide any constructor to create its object so we have to write its static compile() method.
  1. Matcher : A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object.
  1. PatternSyntaxException : A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.
Some Sub-expressions are given below :

Sub-Expressions Description
^ Matches beginning of line.
$ Matches end of line.
. Matches any single character except newline. Using m option allows it to match newline as well.
\w Matches word characters.
\W Matches nonword characters.
\s Matches whitespace.
\S Matches nonwhitespace.
\d Matches digits.
\D Matches nondigits.
{n} Matches exactly n number of occurrences

Example of testing a password string that contains must one lowercase,uppercase,number and spacial character and minimum 6 and maximum 15 characters.
 
// regex Password validation
 
 import java.util.regex.*;

 class reg{
 
 public static void main(String... str) throws Exception{
  
  
  Pattern p=Pattern.compile("(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+-]).{6,15}");
  
  Matcher m=p.matcher("1$6855146146Bbb");
  
  System.out.println(m.matches());
  
 }
 
}

Share this

Related Posts

Previous
Next Post »