Search code examples
regexregex-lookarounds

REGEX to check if a number is repeated in a string


I need a regex that check if a number is repeated in a string of 9 char, knowing that the chars could be an indefinite number of dots

Examples

"........." - false - no numbers repeated
"123456789" - false - no numbers repeated
"1.2.3.4.5" - false - no numbers repeated
"1...3...5" - false - no numbers repeated
"112345678" - true - number 1 is repeated
"1......1." - true - number 1 is repeated
"11244.56." - true - number 1 and 4 are repeated
"234.5.6.4" - true - number 4 is repeated

I found this looking around on internet that is close to what i need

\b(?:([1-9])(?![1-9]*\1)){1,9}\b

But I don't know how to make it not consider dots Thanks very much :)


Solution

  • You can use

    ^(?=.{9}$)(?=.*(\d).*\1)(?:\.*\d){1,9}\.*$
    

    Or, if you need to only allow digits from 1 to 9:

    ^(?=.{9}$)(?=.*([1-9]).*\1)(?:\.*[1-9]){1,9}\.*$
    

    See this regex demo.

    Details:

    • ^ - start of string
    • (?=.{9}$) - the string should contain 9 chars
    • (?=.*(\d).*\1) - there must be a repeating digit
    • (?:\.*\d){1,9}\.* - 1 to 9 occurrences of any zero or more dots followed with a digit and then any zero or more dots
    • $ - end of string.