- 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