charles
charles

Reputation: 384

How to set maxlength in regex?

I have created this working regex below, this aims to accept phone numbers only ex. 09338195838.

^(09)[0-9]{9}

However I don't know how to set a maxlength that will accept only 11 digits. I've been to other similar questions like q1 but none really helped, and tried the below code but still it accepts even if it exceeds to 11 digits.

((09)[0-9]{9}){11}

Here is the detailed structure:

  1. must starts with 09
  2. must all numeric
  3. must 11 digits

Someone knows how to do this?

Upvotes: 2

Views: 2024

Answers (3)

Zoldszemesostoros
Zoldszemesostoros

Reputation: 397

^09[0-9]{9}$
The $ symbol means "The string has to end, without other characters after this".

Upvotes: 3

CoderX
CoderX

Reputation: 302

This is the perfect solution for the mentioned problem: ^09[0-9]{9}$

I am explaining your thoughts.

  • I think you want to wrap the whole regex with max length 11 like this:^(09[0-9]){11}$ it will not work because when you set this{n}, it repeats the previous term with exactly n times. As you wrap the whole term so it will find the match 11 times that start with 09 following any digit(0-9). Ex:(098093095...). so how much time you set it will find full wrap set between the start to end.

    Please check the link I have set a demo example.https://regex101.com/r/JU8JzV/1

Upvotes: 2

Cotur
Cotur

Reputation: 450

You can set word boundry.

((09)[0-9]{9})\b

test: https://regexr.com/51c40

if you want to make it more elastic, not only 11 digit

you can use ((09)\d{0,9})\b

{0,9} sets the min and max lengths, now it accepts maximum 11 digits starts with 09 and min 2 digits that is 09.

Upvotes: 3

Related Questions