3197891abd2c7abb0c8381c7f3b5de282a415e58

Java Regular Expression : Matcher & Pattern

  • Java provides java.util.regex package for regular expression evaluation.
  • It has one interface MatchResault and two derived classes Matcher and Pattern.

Testing Matcher and Pattern:-

  • The following demo code shows use of Matcher and Pattern class use.It also shows the ISBN code validation.
  • A ISBN book code is 13 digit number.

RegularExpressionDemo.java,

package com.sandeep.regular.exp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionDemo {

public static void main(String [] args){

/*matches the input pattern with entire region*/
Pattern buildPattern = Pattern.compile("p*S");
Matcher matcher = buildPattern.matcher("pppppS");
boolean flag = matcher.matches();

System.out.println("Region Matches : "+ flag);

/*replacing first appearnce of p* with 'sandeep' text*/
Pattern groupPattern = Pattern.compile("p*");
Matcher stringMatcher = groupPattern.matcher("pppp ter pppp ter pppp abc");
String modified = stringMatcher.replaceFirst("sandeep");

System.out.println("Modified String: "+modified);

/*A 13 digit ISBN number validation and extraction*/
Pattern pattern = Pattern.compile("(\d-?){13}");
Matcher isbnMatcher = pattern.matcher("ISBN: 978-0-12-345678-9");
while (isbnMatcher.find()){
System.out.println("ISBN Number is valid and number is : "+isbnMatcher.group());
}

}
}

Output:-

Region Matches : true
Modified String: sandeep ter pppp ter pppp abc
978-0-12-345678-9

Download Demo Code:-

Regular Expression Demo Code

Regular Expression Demo Video:-

Sandeep
Capacity & Load Factor : HashMap Jquery DataTables And Java Integration
Sandeep

A passionate Blogger and Developer.Love to code for web application using JavaScript.At present I am exploring the Web Component Specification.

12 years ago java 757

AltStyle によって変換されたページ (->オリジナル) /