找到两次相同的随机模式



如何找到一个字符,如果它总是跟着同一个字母(随机和未知(?

例如:

Kelmqaetrstaeiii

例如,字母a,它后面跟着同一个字母e两次,所以我希望找到它,但有以下内容:

Kelmqaetrstafiii

我们有aeafa后面有2个不同的字母,在这种情况下,什么都不应该被拿走。

可能吗?

您可以遍历字符串并检查字符串中是否已经出现其中一个对:

function hasPair(str) {
const dupe = {};
for (let index = 0; index < str.length - 1; index++) {
const pair = str.substr(index, 2);
if (dupe[pair])
return pair;
dupe[pair] = true;
}
return false;
}
console.log(
hasPair("kelmqaetrstaeii"),
hasPair("kelmqaetrstaii")
);

匹配第一个字母,然后使用前瞻,匹配第二个字母,并使用反向引用:

const re = /(w)(?=(w).+12)/;
console.log('kelmqaetrstaeiii'.match(re)[0]);
console.log('kelmqaetrstafiii'.match(re));

最新更新