Ruby Regex for repeated numbers in a string

流过昼夜 提交于 2019-12-24 18:49:25

问题


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.


回答1:


This regex will detect all repeating groups.

(\d+)(?=.*\1)

Demo

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



回答2:


Try this

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


来源:https://stackoverflow.com/questions/48656838/ruby-regex-for-repeated-numbers-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!