If we want to represent a group of strings according to a particular pattern, then we should go for regular expression.
e.g1. We can write a regular expression to represent all mobile numbers.
e.g2. We can write a regular expression to represent all mail ids.
The main application area of regular expressions are :
A Pattern object represents a compiled version of regular expression. We can create a Pattern object by using compile() method of Pattern class.
public static Pattern compile(String regularExpression);
for exa; Pattern p=Pattern.compile("ab");
here "ab" reprsents a particular pattern.
We can use Matcher object to match the given pattern in the target String. We can create Matcher object using matcher() method of Pattern class.
public Matcher matcher(String target);
for exa; Matcher m=p.matcher("ababbaba");
here "ababbaba" is the target String.
Note : Pattern and Matcher class present in java.util.regex package and introduced in 1.4 versions of Java.
Let's see a demo program for better understanding:
import java.util.regex.*; class RegexDemo { public static void main(String[] args) { // create a Pattern object Pattern p = Pattern.compile("ab"); //create a Matcher object Matcher m = p.matcher("ababbaba"); while (m.find()) { System.out.println(m.start() + "...." + m.end() + "...." + m.group()); } } }
Output
0....2....ab
2....4....ab
5....7....ab
Let's see another program to find the occurrences of "ab" in "ababbaba"
import java.util.regex.*; class RegexDemo1 { public static void main(String[] args) { int count = 0; //create a Pattern object Pattern p = Pattern.compile("ab"); //create a Matcher object Matcher m = p.matcher("ababbaba"); while (m.find()) { count++; System.out.println(m.start() + "...." + m.end() + "...." + m.group()); } System.out.println("the no. of occurrences" + count); } }
Output
0....2....ab
2....4....ab
5....7....ab
the no. of occurences3
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc