❮ Previous Next ❯

Java Regular Expression

If we want to represent a group of strings according to a particular pattern, then we should go for regular expression.

java_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 :

Pattern

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.

Matcher

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.

Methods of Matcher class

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
❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved