简体   繁体   中英

Ruby Regex for repeated numbers in a string

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)

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM