Question: I would like to match the smallest sub string that starts with d and ends with a and contains o.

Example : "djswxaeqobdnoa" => "dnoa"

With this code :

```
Pattern pattern = Pattern.compile("d.*?o.*?a");
Matcher matcher = pattern.matcher("fondjswxaeqobdnoajezbpfrehanxi");
while (matcher.find()) {
  System.out.println(matcher.group());
}

```

The entire input string "djswxaeqobdnoa" printed instead of just "dnoa". Why ? How can I match the smallest ?

Here a solution :

```
String shortest = null;
Pattern pattern = Pattern.compile("(?=(d.*?o.*?a))");
Matcher matcher = pattern.matcher("ondjswxaeqobdnoajezbpfrehanxi");
while (matcher.find()) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
        if (shortest == null || matcher.group(i).length() < shortest.length()) {
            shortest = matcher.group(i);
        }
    }
}

```

Answer: 
Thanks with this code it works :

```
String shortest = null;
Pattern pattern = Pattern.compile("(?=(d.*?o.*?a))");
Matcher matcher = pattern.matcher("ondjswxaeqobdnoajezbpfrehanxi");
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
    if (shortest == null || matcher.group(i).length() < shortest.length()) {
        shortest = matcher.group(i);
    }
}

```

Which is better ?
You are matching the whole `String`, hence the whole `String` is returned by your `group` invocation. 

If you want specific matches of each segment of your `Pattern`, you only need to group those segments. 

For instance:

```
Pattern pattern = Pattern.compile("(d.*?)(o.*?)a");
Matcher matcher = pattern.matcher("djswxaeqobdnoa");
while (matcher.find()) {
    System.out.println(matcher.group());
    // specific groups are 1-indexed
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

```

**Output**

```
djswxaeqobdnoa
djswxaeq
obdno

```