Java regex gets the unbeatable part

I match the regex of the form

abc.*def.*pqr.*xyz 

Now the line abc123def456pqr789xyz will match the pattern. I want to find lines 123, 456, 789 with a match.

What is the easiest way to do this?

+6
java regex
source share
2 answers

Change the regular expression to abc(.*)def(.*)pqr(.*)xyz , and the brackets will be automatically bound to

See the documentation for the class template , especially Groups and Captures , for more information.

Code example:

 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 
+8
source share

Here is a regex that can do what you need.

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

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

+1
source share

All Articles