Norfen
Norfen

Reputation: 11

Regex to match patterns of same numbers

I've been trying to concoct a regex that searches for patterns in numbers. For example, the regex should pull 1725648 out of 172564817256481725648.

Currently, I've got (\\d+){1+}, but it's just returning blank.

Upvotes: 1

Views: 133

Answers (2)

stema
stema

Reputation: 92986

This will work on your example

^(\d+)\1+$

See it here on Regexr

You can get the found pattern from group 1.

This will match sequences of the same digit sequence. \1 is a backreference to what is matched in (\d+). I put a + behind it, so it would need to match this sequence till the end. ^ anchors it to the start of the string and $ to the end.

But your requirements are not very clear. See this

(\d+).*\1

It is missing the anchors and allows stuff .* in between searched pattern. But it will find only the first sequence in string, that is repeated later in the string.

Hello1725648Foo987Bar987Foobar1725648  
     |||||||__________________|||||||

it will find 1725648

He987llo1725648FooBar987Foobar1725648
  |||________________|||

it will find 987

123He987llo1725648FooBar987Foobar1725648
|________________________________|

it will find only 1

Upvotes: 2

dcp
dcp

Reputation: 55444

I don't think you're going to find a regex to do that. You need more powerful mechanisms to do what you're looking for, one such is the Robin-Karp algorithm.

Upvotes: 4

Related Questions