Search code examples
regexrepeatquantifiers

Regex repetition


I'm trying to perform a regex replacement. Therefor I defined the following expression:

    ^(?:9903[0]*([0-9]*)){20}$

This Expression should match to

    99030000000000000001
    99030000000000000011
    99030000000000000111
    99030000000000001111
    99031111111111111111

but not to

    9903111111111111111

In fact, the expression above does not work until I either use {1,20} as quantifier or remove it completely. But as I want to check the length of the whole string without knowing the length of [0]* nor the length of the variable, there's something wrong with my expression.

Many thanks for your help in advance.

D


Solution

  • There are multiple things wrong with your initial regex.

    The {} part is applied to en entire part between brackets. So your current regex requires that this part:

    (?:9903[0]*([0-9]*))
    

    Is repeated 20 times in its entirety, which is not what you want.

    Then this part:

    [0]*([0-9]*)
    

    Makes little sense, do you want to capture the number after 9903 without the leading zeros? Then require that the capture starts with a non-zero number. [0] is a character class with just one character, equivalent to just 0.

    Concluding, I would do it like so:

    ^9903(?=[0-9]{16}$)0*([1-9][0-9]*)$
    

    Regex101

    Edit: I realized later that if it's required to match 99030000000000000000 (get 0 in your capture group) then you need this:

    ^9903(?=[0-9]{16}$)0*([0-9]+)$
    

    Regex101