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?
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?
Change the regex to abc(.*)def(.*)pqr(.*)xyz
and the parentheses will be automatically bound to
$1
through $3
if
you use String.replaceAll() orSee 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
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.