Regular Expressions


Regular expressions
Java Regex

The Java Regex serves as an API to define pattern for searching strings.
It is used to define constraint on a given strings like password validation or for email validation. After going through this java regex tutorial, you can test your own regular expressions!!
java.util.regex package
It provides classes and interface for making the regular expressions. The Matcher alongwith Pattern classes are widely used in java regular expression.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class

[java] import java.util.regex.*;

public class Regex{
public static void main(String args[])
Pattern p = Pattern.compile(“.p”);
Matcher m = p.matcher(“pen”);
boolean c = m.matches();
boolean c2=Pattern.compile(“.p”).matcher(“pen”).matches();
boolean c3 = Pattern.matches(“.p”, “pen”);
System.out.println(c+” “+c2+” “+c3);

[/java] Output
true true true

Regex Character classes
No. Character Class   Description
1     [abc]               a, b, or c (simple class)
2     [^abc]             Any character except a, b, or c (negation)
3     [a-zA-Z]          a through z or A through Z, inclusive (range)
4     [a-d[m-p]]       a through d, or m through p: [a-dm-p] (union)
5     [a-z&&[def]]    d, e, or f (intersection)
6     [a-z&&[^bc]]    a through z, except for b and c: [ad-z] (subtraction)
7    [a-z&&[^m-p]]   a through z, and not m through p: [a-lq-z](subtraction)

Facebook Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.