Search code examples
c#regexvalidationstring-matching

Regex for matching string, contains only number and count must be 2 min values


Is there any regex for validating length of a number string for 2 consecutive digits or number

Example :

"12541256442545245215" = Count (20)
"125412564425452452"= Count (18)

Need a regex to check a string which contains only number and count must be 18 or 20.

I tried using the below regex but it allows length 19 also.

^[0-9.]{18,20}$

Solution

  • You can use this regex:

    ^[0-9.]{18}(?:[0-9.]{2})?$
    

    About this regex:

    ^            # start
    [0-9.]{18}   # match digit or DOT 18 times
    (?:          # start non-capturing group
       [0-9.]{2} # match digit or DOT 2 times
    )?           # end non-capturing group, ? makes this group *optional*
    $            # end
    

    If you don't want to allow DOT then use:

    ^[0-9]{18}(?:[0-9]{2})?$