如何匹配 java 中的两个模式?
How to match two patterns in java?
我能够使用以下代码在两个字符串(sss 和 eee)之间提取数据
例如的味精:
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);
}
我在 detect_start -> ,data1,data2,data3,
中得到了正确的值
现在我想匹配两个模式
模式 r = Pattern.compile("sss(.*?)eee");
模式ack_r = Pattern.compile("ack(.?)received");
怎么做?
我尝试了以下行,但它给出了不允许的错误
匹配器 m = r.matcher(msg) || ack_r.matcher(消息);
我尝试了以下逻辑,但它不起作用(仅匹配第一个模式)
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);
}
您可以在此处使用单个正则表达式交替:
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
我能够使用以下代码在两个字符串(sss 和 eee)之间提取数据
例如的味精: 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);
}
我在 detect_start -> ,data1,data2,data3,
中得到了正确的值现在我想匹配两个模式
模式 r = Pattern.compile("sss(.*?)eee");
模式ack_r = Pattern.compile("ack(.?)received");
怎么做?
我尝试了以下行,但它给出了不允许的错误
匹配器 m = r.matcher(msg) || ack_r.matcher(消息);
我尝试了以下逻辑,但它不起作用(仅匹配第一个模式)
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);
}
您可以在此处使用单个正则表达式交替:
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