Ruby 字符串中重复数字的正则表达式

Ruby Regex for repeated numbers in a string

如果我有一个像 "123123123" 这样的字符串 - 这里 123 重复了 3 次。
1. 那么如何才能在 ruby 中只得到 "123"
2. 因此,如果字符串是 "12312312" - 这里 123 重复了 2 次,然后只是 12,所以这里我仍然需要得到 "123"
3. 即使字符串是99123123123,我仍然需要得到123
这在 Ruby 正则表达式中可能吗?

编辑:我想要这个来解决 Project Euler Problem 26 。所以这里 123 可以是任何东西。我只想提取 1 个至少 2 个重复的数字。

试试这个

99123123123.scan(/123/).count
12312312.scan(/123/).count

此正则表达式将检测所有重复组。

(\d+)(?=.*)

Demo

与 ruby 搭配也很好。

result = '9912341234123'.scan(/(\d+)(?=.*)/)
#gets group with largest length
longestRepeatingGroup = result.max_by{|arr| arr[0].length}

puts longestRepeatingGroup
puts longestRepeatingGroup[0].length