本文介绍了在Java正则表达式中与多个模式重叠匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到与
但有多种模式。我的正则表达式如下:
but with multiple patterns. My regex is like:
Pattern word = Pattern.compile("([\w]+ [\d]+)|([\d]+ suite)|([\w]+ road)");
如果我的示例文本是,
我的愿望输出是,
123套房
但我得到了
仅限。
提前致谢!
推荐答案
您可以尝试使用正向前瞻断言的以下正则表达式。
You could try the below regex which uses positive lookahead assertion.
(?=(\b\w+ Road \d+\b)|(\b\d+ suite\b))
String s = "XYZ Road 123 Suite";
Matcher m = Pattern.compile("(?i)(?=(\\b\\w+ Road \\d+\\b)|(\\b\\d+ suite))").matcher(s);
while(m.find())
{
if(m.group(1) != null) System.out.println(m.group(1));
if(m.group(2) != null) System.out.println(m.group(2));
}
输出:
XYZ Road 123
123 Suite
这篇关于在Java正则表达式中与多个模式重叠匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!