Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex get unmatched portion

Tags:

java

regex

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?

like image 631
Rohit Banga Avatar asked Sep 20 '10 13:09

Rohit Banga


1 Answers

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

  • the variables $1 through $3 if you use String.replaceAll() or
  • Matcher.group(n) if you use Matcher.find()

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
like image 87
Sean Patrick Floyd Avatar answered Oct 02 '22 17:10

Sean Patrick Floyd