Regexp detect repeating number

Hi,

I want to detect a repeating number in a string; something like:
252525252525 or 123123123
regards,

rubix Rubix [email protected] writes:

Hi,

I want to detect a repeating number in a string; something like:
252525252525 or 123123123
regards,

This seems to work:

regexp = /(\d+?)(?=\1)/

'252525252525'[regexp]            # => "25"
'123123123'[regexp]               # => "123"
'1223122312231223'[regexp]        # => "1223"

Thx,
it works but I want to understand what does mean the two parts:
(\d+?)and (?=\1)
and what to add if I want to detect an exact time of repeating
regards,

rubix Rubix [email protected] writes:

Thx,
it works but I want to understand what does mean the two parts:
(\d+?)and (?=\1)
and what to add if I want to detect an exact time of repeating
regards,

group (\d+?) ‘reluctantly’ (as opposed to ‘greedy’) matches some
sequence of digits.

(?=\1) performs look-ahead operation, which specifies, that to the right
of the first group should be it’s copy.

To detect repetition count you can simply divide length of whole string
by length of repeating fragment.

This solution is simpler, a little more robust and refactored to
separate functions:

def repeated_digits(string)
string[/^(\d+?)\1*$/, 1]
end

def repetition_count(string)
string.length / repeated_digits(string).length
end

repeated_digits ‘252525252525’ # => “25”
repetition_count ‘252525252525’ # => 6

repeated_digits ‘123123123’ # => “123”
repetition_count ‘123123123’ # => 3

repeated_digits ‘1223122312231223’ # => “1223”
repetition_count ‘1223122312231223’ # => 4

no repetition:

repeated_digits ‘123344453453454354’ # => “123344453453454354”
repetition_count ‘123344453453454354’ # => 1