Ruby Regex用于字符串中的重复数字 [英] Ruby Regex for repeated numbers in a string
问题描述
如果我有一个类似 123123123
的字符串-在这里 123
重复3次。
1.那么我怎么只能得到 123
的红宝石?
2.因此,如果字符串为 12312312
-这里 123
重复2次,然后只是 12
,所以在这里我仍然需要获取 123
。
3.即使字符串为 99123123123
,我仍然需要获取 123
。
在Ruby Regex中可能吗?
编辑:我希望它解决 Project Euler Problem 26 。因此,这里 123
可以是任何东西。我只想提取至少两个重复数字中的1个。
此正则表达式将检测所有重复组。 / p>
(\d +)(?=。* \1)
效果很好
result ='9912341234123'.scan(/(\d +)(?=。* \1 )/)
#获取长度最大的组
longestRepeatingGroup = result.max_by {| arr | arr [0] .length}
放入longestRepeatingGroup
放入longestRepeatingGroup [0] .length
If i have a string like "123123123"
- Here 123
is repeated 3 times.
1. So how can i get only "123"
in ruby?
2. So if the string is "12312312"
- Here 123
is repeated 2 times and then just 12
, so here still i need to get "123"
.
3. Even if string is 99123123123
, still i need to get 123
.
Is this possible in Ruby Regex?
EDIT: I want this to solve Project Euler Problem 26 . So here 123
can be anything. All i want is to extract 1 number of at-least 2 repeated numbers.
This regex will detect all repeating groups.
(\d+)(?=.*\1)
Works great with ruby too.
result = '9912341234123'.scan(/(\d+)(?=.*\1)/)
#gets group with largest length
longestRepeatingGroup = result.max_by{|arr| arr[0].length}
puts longestRepeatingGroup
puts longestRepeatingGroup[0].length
这篇关于Ruby Regex用于字符串中的重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!