如何用正则匹配字符串中重复字母?Ruby正则问题求助与调试
Hey there! I get why you're confused here—let's clear this up step by step.
The Problem with Your Original Regex
The regex /[a-z]{2,}/ matches consecutive sequences of 2 or more identical lowercase letters. For example, in "hello", it would catch "ll", and in "aabbcc" it would grab "aa", "bb", and "cc".
But if you're trying to target letters that appear two or more times anywhere in the string (not just back-to-back)—like the a and b in "abab"—this regex falls flat. It only checks for runs of identical consecutive characters, not the total count of a letter across the entire string. That's why it wasn't working for your use case.
The Correct Regex for Your Use Case
If your goal is to find any lowercase letter that repeats at least twice in the string (regardless of position), here's how to do it in Ruby:
Extract All Repeating Letters
Use this regex combination with scan, uniq, and flatten to get a clean list of letters that appear multiple times:
sample_string = "abracadabra" repeating_letters = sample_string.scan(/([a-z])(?=.*\1)/).uniq.flatten # Returns ["a", "b", "r"]
Let's break down the regex:
([a-z]): Captures a single lowercase letter and stores it in group 1.(?=.*\1): A positive lookahead that verifies the captured letter (\1) appears again somewhere later in the string. This guarantees the letter shows up at least twice total.
We use uniq because the regex will match the same repeating letter multiple times (like the a in "abracadabra" being flagged every time it's followed by another a). flatten turns the nested array output from scan into a simple, readable list.
If You Actually Wanted Consecutive Repeats
If you did mean to match consecutive repeated letters but it still wasn't working, double-check two things:
- Add the
imodifier if you need to match uppercase letters too:/[a-z]{2,}/i - Confirm your string actually has consecutive repeats (e.g.,
"abba"has"bb", but"abab"doesn't)
Example Test Case
Let's test with the string "abab" where your original regex failed:
str = "abab" # Original regex: no matches found str.match(/[a-z]{2,}/) # => nil # Fixed approach: correctly identifies repeating letters str.scan(/([a-z])(?=.*\1)/).uniq.flatten # => ["a", "b"]
内容的提问来源于stack exchange,提问作者Avery

