jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Pattern and matcher Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Pattern and matcher" Watch "Pattern and matcher" New topic

Pattern and matcher

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi, I got it from ExamLab practice1,

import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;

public class Expons{

static Stores st;

public static void main(String argv[]){
st=new Stores();
Object ob1=getFormattedObject(Pattern.compile("H[a-d][k-m]"), "H[a-b][k-m]");
Object ob2=getFormattedObject(st.pt1.matcher("Hello Hallo"), "[a-e][l]lo");
Object ob3=getFormattedObject(null);

public static Object getFormattedObject(Object ob, String... s){
if (ob instanceof Pattern){
return null;
}else if (ob instanceof Matcher){
return null;
return st.st1;


class Stores{
Pattern pt1; Matcher mt1; String st1;

output is: Hal

Can anyone explain me the working of pattern and matcher class with the above arguments.
i am confused which one is regular expression in pattern class and which is string for matcher class....

please clarify this...

Ankit Garg

Joined: Aug 03, 2008
Posts: 9435

It's a nice question! Here's what actually happens in the code

Pattern p = Pattern.compile("H[a-d][k-m]");
Matcher m = p.matcher("Hello Hallo");
String s = m.group();

Now that you have an idea what the code actually does, just follow the execution process and you will realize what is happening...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231
The program flow is complicated to confuse you.

In essence you are just achieving, the result of applying the
expression "H[a-b][k-m]" on the source string "Hello Hallo".

Applying the regex pattern search will give you "Hal" as the matching string from the source.

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi Ankit,
I am ok with the sample code you gave, the only thing i am not getting is below,

Object ob1=getFormattedObject(Pattern.compile("H[a-d][k-m]"), "H[a-b][k-m]");
Object ob2=getFormattedObject(st.pt1.matcher("Hello Hallo"), "[a-e][l]lo");

and st.pt1=((Pattern)ob).compile(s[0]); // here it has to take s[0] which meant H[a-b][k-m] to match the String.
here i am confused with...

Himalay Majumdar
Ranch Hand

Joined: Sep 28, 2008
Posts: 324

Yes..the pattern set here is H[a-b][k-m]..that is what Ankit indicated. It matches 'H' from Hello and 'al' from Hallo...(Lallan Speaking..)
[ December 23, 2008: Message edited by: Himalay Majumdar ]

SCJP 1.6, SCWCD 5.0, SCBCD 5.0 [loading..]
I agree. Here's the link: http://aspose.com/file-tools
subject: Pattern and matcher
It's not a secret anymore!