1

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!

1
  • 1
    could you explain your needs? Commented Dec 26, 2014 at 11:21

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

If I have some 15k groups, may i need to add 15k if blocks?
In the above example I have 2 groups ie., 2 regex patterns to match. So as you specified I can get the matched text using m.group(1), m.group(2). Similarly If I have 15k groups(regex patterns) what I need to do?
then it's better to use a for loop.
1
(?=(\b[\w]+ [\d]+))|(?=(\b[\d]+ suite))|(?=(\b[\w]+ road))

Try this.See demo.Grab the captures.

https://regex101.com/r/dU7oN5/16

Use positive lookahead to avoid string being consumed.

Comments

0

Something like this, maybe?

Pattern p = Pattern.compile("([\\w ] Road) (\\d+) (Suite)");
Matcher m = p.matcher(input);
if(m.find) {
   System.out.println(m.group(1) + " " + m.group(2));
   System.out.println(m.group(2) + " " + m.group(3));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.