articles

Home / DeveloperSection / Articles / Java Regex or Regular Expression in java

Java Regex or Regular Expression in java

Anupam Mishra 5366 09-Nov-2015

The Regular Expression is an API to define pattern for searching or manipulating strings.

Java Regex API provides 1 interface and 3 classes in java.util.regex package i.e.

1.    MatchResult interface

2.    Matcher class

3.    Pattern class

4.    PatternSyntaxException class

The Matcher and Pattern classes are widely used in java regular expression.

Matcher Class:


It implements MatchResult interface. It is a regex engine i.e. used to perform

match operations on a character sequence.

Pattern Class:

It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.

For Example, we see the implementation of java regex with the help of following example 

import java.util.regex.*;  
public class RegexEx{ 
public static void main(String args[]){ 
//First way  Pattern p = Pattern.compile(".s");//compiles the given regex and return the instance of pattern.
Pattern q = Pattern.compile("a.");
//. represents single character in Regular Expression
 
Matcher m = p.matcher("as"); //creates a matcher that matches the given input with pattern.
boolean b = m.matches();/*It compiles the regular expression and matches the given input with the pattern.  */
 
//Second  way 
 boolean b2=Pattern.matches("[amn]", "a");//true (among a or m or n)   
//Third way  boolean b3 = Pattern.matches("[amn]", "a"); 
boolean b4 = Pattern.matches("a.", "as");
System.out.println(b+" "+b2+" "+b3+" "+b4);
// another operations
System.out.println("metacharacters d...."); //d means digit 
System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit) 
System.out.println(Pattern.matches("\\d", "1")); //true (digit and comes once)   
System.out.println("metacharacters D....");//D means non-digit   
System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)
System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)
 
System.out.println("metacharacters D with quantifier...."); 
System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or more times) 
 }

The output of the above program is shown below:


Updated 27-Mar-2018

Leave Comment

Comments

Liked By