4
How is regex to validate the following rule:
- Numbers only;
- A maximum of 6 numbers, and a minimum of 1;
- The first number needs to be different from 0;
I tried it this way and it didn’t work:
/^[1-9]+(\d){0,5}$/
What’s the mistake?
4
How is regex to validate the following rule:
I tried it this way and it didn’t work:
/^[1-9]+(\d){0,5}$/
What’s the mistake?
4
The problem is in +
in [1-9]+
.
The quantifier +
means "one or more occurrences", therefore [1-9]+
takes one or more occurrences of digits from 1
to 9
.
If you want exactly one digit of 1
to 9
, just remove the +
:
/^[1-9]\d{0,5}$/
And also note that you don’t need parentheses around the \d
, therefore, \d{0,5}
already taken from zero to five digits of 0
to 9
.
How was not said which language/engine/tool you are using, I think it is worth mentioning that the shortcut \d
, depending on the language/engine/tool, can also consider any character of the Unicode category "Number, Decimal Digit". This includes not only the digits of 0
to 9
, but also several other characters representing digits, such as ٢
(ARABIC-INDIC DIGIT TWO), among others.
If the idea is to ensure only digits of 0
to 9
, can change to:
/^[1-9][0-9]{0,5}$/
But of course if you’re wearing one engine in which \d
is equivalent to [0-9]
(or if you know that your data will never have the other characters already cited), then either use one or the other.
Browser other questions tagged regex
You are not signed in. Login or sign up in order to post.
It worked, thank you!
– V. Rodrigues