Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何使用正则表达式查找重复字符?
如果我有aaabbab,我只想匹配具有三个重复的字符:
aaabbab
aaa
试试看string.scan(/((.)\2{2,})/).map(&:first),string你的字符串在哪里。
string.scan(/((.)\2{2,})/).map(&:first)
string
它的工作方式是它查找任何字符并捕获它(点),然后匹配该字符的重复(\2反向引用)2 次或更多次({2,}范围表示“2 到无限次之间的任何地方”)。Scan 将返回一个数组数组,因此我们将第一个匹配项映射出来以获得所需的结果。
\2
{2,}