A Regular Expression is a expression which representsa group of Strings according to a particular pattern.
Example:
We
can write a Regular Expression to represent all valid mail ids.
We can write a Regular
Expression to represent all valid mobile numbers.
The main important application areas of Regular
Expression are:
To implement validation logic.
To develop Pattern matching applications.
To develop translators like
compilers,interpreters etc.
To develop digital circuts.
Example:
Import java.util.regex.*;
Class RegularExp
{
public
static void main(String args[])
{
int
count = 0;
Pattern
p = Pattern.compile(“ab”)
Matcher
m = p.matcher(“abbbabbaba”);
while(m.find())
{
count++;
System.out.println(m.start()+”-----”+m.end()+”-
-----”+m.group());
-----”+m.group());
}
System.out.println(“no of
occurences”+count);
}
}
Output:
0------2------ab
4------6------ab
7------9------ab
The no of occurrences: 3
Pattern:
Pattern is a class present in java.util.regex.Pattern package.
It
was implemented by Serializable Interface.
By
using compile() method we can create an object for Pattern class.
Syntax: public static Patterncompile(String regex);
Example: Pattern =
Pattern.compile(“ab”);
Matcher:
After
creating Pattern object, It can be used to create a Matcher object.
This
Matcher Object can match arbitrary character sequence against the regular
expression.
Syntax: public Matchermatcher(String target);
Example: Matcher
m=p.matcher("abbbabbaba");
0 comments:
Post a Comment