gpt4 book ai didi

javascript - 正则表达式提取所有重复字符

转载 作者:行者123 更新时间:2023-12-01 08:12:56 25 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来提取字符串中的所有重复字符。它们不需要连续。所以对于字符串 abacb 我想提取 [a, b]

不幸的是,我只能想出给我 a 的方法。喜欢:

    /(\w).+?(?:\1)/.exec('abacb');
// Array [ "aba", "a" ]

我们将不胜感激!

最佳答案

使用 String.prototype.match() 的简短解决方案具有特定正则表达式模式的函数:

var str = 'abacb',
result = str.match(/(\w)(?=.*?\1)/g);

console.log(result);

(\w) - 第一个包含重复字符的捕获组

\1 - 对第一个捕获组的反向引用(意味着某些字符重复)


要仅获取唯一的匹配字符,请使用 Array.prototype.filter()Array.prototype.lastIndexOf() 函数:

var str = 'aaaaabcbaa',
result = str.match(/(\w)(?=.*?\1)/gm);

if (result) {
result = result.filter(function(c, i, a) { return i === a.lastIndexOf(c); })
}
console.log(result);

或者 Ecmascript6 使用 Set 的方法对象和 spread operator :

var str = 'aaaaabcbaa',
result = str.match(/(\w)(?=.*?\1)/gm);

if (result) {
result = [...new Set(result)];
}
console.log(result);

关于javascript - 正则表达式提取所有重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42058009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com