如何在java中匹配两种模式?

t9eec4r0  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(458)

我能够使用下面的代码在两个字符串(sss和eee)之间提取数据
e、 g.of msg:msg=“adg sss,数据1,数据2,数据3,eee”;

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

String  detect_start = null;

Matcher m = r.matcher(msg) ;

                    while(m.find())
                    {
                        detect_start = m.group(1);
                    }

我在detect_start->、data1、data2、data3中得到了正确的值,
现在我想匹配两种模式
模式r=pattern.compile(“sss(.*eee”);
pattern ack_r=pattern.compile(“收到确认(.?));
怎么做?
我试着在下面的线,但它给出了错误,这是不允许的
匹配器m=r.matcher(msg)|确认匹配器(msg);
我尝试了下面的逻辑,但它不起作用(只匹配第一个模式)

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);
}
4nkexdtk

4nkexdtk1#

您可以在此处使用单个正则表达式替换:

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);
}

这张照片是:

,data1,data2,data3,
 blah blah

相关问题