Q:

Getting overlapping matches with multiple patterns in Java regex

I have the same problem as in this link
but with multiple patterns. My regex is like:
Pattern word = Pattern.compile("([\w]+ [\d]+)|([\d]+ suite)|([\w]+ road)");

If my sample text is,

XYZ Road 123 Suite

My desire output is,

XYZ Road 123
123 suite

But am getting

XYZ Road 123

only.
Thanks in advance!

A:

You could try the below regex which uses positive lookahead assertion.
(?=(\b\w+ Road \d+\b)|(\b\d+ suite\b))

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

Output:
XYZ Road 123
123 Suite

