G.ONE
G.ONE

Reputation: 537

How to match two patterns in java?

i am able to extract data between two strings(sss & eee) using below code

e.g. of msg : msg = "adg sss ,data1,data2,data3,eee";

Pattern r = Pattern.compile("sss(.*?)eee");
                
String  detect_start = null;

Matcher m = r.matcher(msg) ;
                 
                    while(m.find())
                    {
                        detect_start = m.group(1);
                    }

I get correct values in detect_start -> ,data1,data2,data3,

Now i want to match two patterns

Pattern r = Pattern.compile("sss(.*?)eee");

Pattern ack_r = Pattern.compile("ack(.?)received");

How to do it ?

I tried below line but it gives error that its not allowed

Matcher m = r.matcher(msg) || ack_r.matcher(msg) ;

I tried below logic but it doesn't works(only matches first pattern)

Pattern r = Pattern.compile("sss(.*?)eee");
 Pattern ack_r = Pattern.compile("ack(.?)received");                   
    String  detect_start = null;
  String detect_ack = null;
    Matcher m = r.matcher(msg) ;
Matcher m_ack = ack_r.matcher(msg);
                     
                        while(m.find())
                        {
                            detect_start = m.group(1);
                        }
                      while(m_ack.find());
{
         detect_ack = m_ack.group(1);
}

Upvotes: 1

Views: 727

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520948

You may use a single regex alternation here:

String msg = "adg sss,data1,data2,data3,eee ack blah blah received";
Pattern r = Pattern.compile("sss(.*?)eee|ack(.*?)received");                   
Matcher m = r.matcher(msg);

while(m.find()) {
    String match = m.group(1) != null ? m.group(1) : m.group(2);
    System.out.println(match);
}

This prints:

,data1,data2,data3,
 blah blah 

Upvotes: 2

Related Questions