6

I am matching a regex of the form

abc.*def.*pqr.*xyz

Now the string abc123def456pqr789xyz will match the pattern. I want to find the strings 123, 456, 789 with the matcher.

What is the easiest way to do this?

2 Answers 2

8

Change the regex to abc(.*)def(.*)pqr(.*)xyz and the parentheses will be automatically bound to

See the documentation of the Pattern class, especially Groups and Capturing, for more info.

Sample Code:

final String needle = "abc(.*)def(.*)pqr(.*)xyz";
final String hayStack = "abcXdefYpqrZxyz";

// Use $ variables in String.replaceAll()
System.out.println(hayStack.replaceAll(needle, "_$1_$2_$3_"));
// Output: _X_Y_Z_


// Use Matcher groups:
final Matcher matcher = Pattern.compile(needle).matcher(hayStack);
while(matcher.find()){
    System.out.println(
        "A: " + matcher.group(1) +
        ", B: " + matcher.group(2) +
        ", C: " + matcher.group(3)
    );
}
// Output: A: X, B: Y, C: Z
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a regex that might do what you need.

abc(\\d*)def(\\d*)pqr(\\d*)xyz

But, we should have more examples of input strings, and what should be matched.

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.