java - Efficiently finding all overlapping matches for a regular expression -


this followup all overlapping substrings matching java regex.

is there way make code faster?

public static void allmatches(string text, string regex) { (int = 0; < text.length(); ++i) { (int j = + 1; j <= text.length(); ++j) { string positionspecificpattern = "((?<=^.{"+i+"})("+regex+")(?=.{"+(text.length() - j)+"}$))"; matcher m = pattern.compile(positionspecificpattern).matcher(text); if (m.find()) { system.out.println("match found: \"" + (m.group()) + "\" @ position [" + + ", " + j + ")"); } } } } 

in other question mentioned matcher's region() method, weren't making full use of it. makes valuable anchors match @ region's bounds if bounds of standalone string. that's assuming you've got useanchoringbounds() option set, that's default setting.

public static void allmatches(string text, string regex) { matcher m = pattern.compile(regex).matcher(text); int end = text.length(); (int = 0; < end; ++i) { (int j = + 1; j <= end; ++j) { m.region(i, j); if (m.find()) { system.out.printf("match found: \"%s\" @ position [%d, %d)%n", m.group(), i, j); } } } } 

given sample string , regex:

allmatches("string t = 04/31 412-555-1235;", "^\\d\\d+$"); 

...i output:

match found: "04" @ position [11, 13) match found: "31" @ position [14, 16) match found: "41" @ position [17, 19) match found: "412" @ position [17, 20) match found: "12" @ position [18, 20) match found: "55" @ position [21, 23) match found: "555" @ position [21, 24) match found: "55" @ position [22, 24) match found: "12" @ position [25, 27) match found: "123" @ position [25, 28) match found: "1235" @ position [25, 29) match found: "23" @ position [26, 28) match found: "235" @ position [26, 29) match found: "35" @ position [27, 29) 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -