regex - Java regular expression nongreedy issue -
i match smallest sub string starts d , ends , contains o.
example : "djswxaeqobdnoa" => "dnoa"
with 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 "dnoa". why ? how can match smallest ?
here solution :
string shortest = null; pattern pattern = pattern.compile("(?=(d.*?o.*?a))"); matcher matcher = pattern.matcher("ondjswxaeqobdnoajezbpfrehanxi"); while (matcher.find()) { (int = 1; <= matcher.groupcount(); i++) { if (shortest == null || matcher.group(i).length() < shortest.length()) { shortest = matcher.group(i); } } }
djswxaeqobdnoa d....*..o..*.a
that's 1 match of regular expression consuming full string
.
Comments
Post a Comment