这是一个匹配包含所有“a”、“b”和“c”的 5 个字母序列的正则表达式:
(?=.{0,4}a)(?=.{0,4}b)(?=.{0,4}c).{5}
因此,虽然基本上匹配任何 5 个字符(带有.{5}),但匹配必须遵守三个先决条件。它们中的每一个都需要存在一个标记/字母(最多 4 个字符,后跟“a”等)。(?=X)匹配“X,零宽度正向预读”,其中零宽度表示匹配时不移动字符位置。
但是,使用正则表达式执行此操作很慢。这是一个更直接的版本(似乎比使用正则表达式快 15 倍):
public static void find(String haystack, String tokens, int windowLen) {
char[] tokenChars = tokens.toCharArray();
int hayLen = haystack.length();
int pos = 0;
nextPos:
while (pos + windowLen <= hayLen) {
for (char c : tokenChars) {
int i = haystack.indexOf(c, pos);
if (i < 0) return;
if (i - pos >= windowLen) {
pos = i - windowLen + 1;
continue nextPos;
}
}
// match found at pos
System.out.println(pos + ".." + (pos + windowLen - 1) + ": " + haystack.substring(pos, pos + windowLen));
pos++;
}
}