How to create a regular expression to accept only upto 12 digits? Many Thanks
Asked
Active
Viewed 2,239 times
-2
-
3Read some regex tutorial, shouldn't be too difficult. – Sebastian Proske Oct 29 '16 at 19:12
-
http://stackoverflow.com/a/1649441/362536 – Brad Oct 29 '16 at 19:14
2 Answers
3
/^\d{0,12}$/
... which breaks down as ...
/ # start regex
^ # anchor to start of string
\d # 0-9
{0,12} # 0-12 times
$ # anchor end of string
/ # end regex

Billy Moon
- 57,113
- 24
- 136
- 237
0
(?:^|[^0-9])([0-9]{1,12})(?![0-9])
I have divided problem to 3 part according to answers.
- Problem want to does not start with digit
(?:^|[^0-9]) means that starts with non digit character or does not start with any character
- Problem want to consume 12 digit:
[0-9] means that we want to consume just digits
{1,12} means that we want to consume up to 12 character
- Problem want to does not consume these 12 digit if 13rd character is digit also.
? means that look but does not consume
![0-9] means that this character could be everything except digit.

M S
- 2,455
- 1
- 9
- 11
-
If for example, a string contains only 13 digits followed by an other character that is not a digit, your pattern will match too, not at the position 0 but at the position 1. If the string contains only 12 digits the pattern will fail too since there isn't a 13th character to make `(?=[^0-9])` to succeed. – Casimir et Hippolyte Oct 29 '16 at 19:33
-
-
Take care to refresh the page since I have edited my comment several times. – Casimir et Hippolyte Oct 29 '16 at 19:39
-
As an aside, whatever what you answer, it's basically a crappy question (too broad, no effort... === Off topic), so don't bother about it. – Casimir et Hippolyte Oct 29 '16 at 19:43
-
When you want to look around in javascript (that doesn't support lookbehind), you can ends your pattern with a negative lookahead (like `(?![0-9])` that is equivalent to `(?=[^0-9]|$)`) and you need to start with an alternation like that: `(?:^|[^0-9])`. To extract the twelve digits, the only way is to use a capture group. – Casimir et Hippolyte Oct 29 '16 at 19:56
-
Yes I have looked up for lookbehind implementation in javascript. But have not implemented yet. Your start alternation works with consuming 1 character. Because of that if you want to operation with that you should make group for first character that is not digit. Anyway i think we will find most correct answer :) – M S Oct 29 '16 at 20:19
-
Perhaps, but since nobody knows if he is looking for a pattern that searches for twelve digits in a text or if he's looking for a pattern that validates only twelve digits strings, it remains too broad. – Casimir et Hippolyte Oct 29 '16 at 20:35
-