Mych
Mych

Reputation: 2553

RegEx match 7 to 11 digits with or without prefix

Hi I need a regex that will match a min of 7 digits to a max of 11 digits with an optional prefix of ptno or PTNO

I currently have...

^[pP]?[tT]?[nN]?[oO]?[0-9]+$

But this matches any number of digits... How do I restrict to min 7 or max 11 digits.

The following show valid and invalid combinations

PTNO01234567891     (valid max no of digits) 
12345678901         (valid max no of digits) 
PTNO9876543         (valid min no of digits) 
1234567             (valid min no of digits) 
PTNO000012345678    (invalid too many digits) 
012345678912        (invalid too many digits) 
PTNO098765          (invalid too few digits) 
123456          (invalid too few digits)

Actually I would be happy to have a regex that will take a value disregard optional prefix and any padded 0 and from what is left make sure I have a min of 7 digits.

Upvotes: 2

Views: 1628

Answers (3)

wumpz
wumpz

Reputation: 9131

Try this regexp:

^(ptno|PTNO)?\d{7,11}$

Regular expression visualization

Debuggex Demo

I am not sure about your meaning of "prefix of ptno or PTNO". In your example you are allowing skipping of single letters here (PNO would match). I did a complete match of this prefix.

Upvotes: 1

tenub
tenub

Reputation: 3446

What about using case-insensitive flag with the following:

^(?:ptno)?0*\d{7,}$

And if it should only be ptno or PTNO:

^(?:ptno|PTNO)?0*\d{7,}$

Upvotes: 0

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Change the + sign int {7,11} from your regex. + means one or more, that's why it is matching any amount of digits having more than 1:

^[pP]?[tT]?[nN]?[oO]?[0-9]{7,11}$

Upvotes: 1

Related Questions