-2

How to create a regular expression to accept only upto 12 digits? Many Thanks

Kalyani Kirad
  • 309
  • 3
  • 12

2 Answers2

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.

  1. Problem want to does not start with digit

(?:^|[^0-9]) means that starts with non digit character or does not start with any character

  1. 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

  1. 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
  • @CasimiretHippolyte Yes I will see that point. I will update my answer – M S Oct 29 '16 at 19:38
  • 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
  • @CasimiretHippolyte yes because of the crappy question. – M S Oct 29 '16 at 20:37