Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Match Character and Max Length

I am trying to create a regular expression in javascript that will match these requirements

  • Starts with a 0 but second digit not a 0
  • 11-12 characters long
  • Must contain exactly 1 space
  • No other special characters or letters, just numbers

So far I have come up with ^[0][1-9][\d ]{9,10}$

however, this would still match with 2 spaces or no spaces. I have been so far unsuccessful to find a way to require just one space anywhere within the number. I have tried positive lookahead and found other examples online, however making the quantifier work with the requirement has proven difficult.

like image 967
Lotok Avatar asked Dec 05 '22 00:12

Lotok


2 Answers

You can use

/^(?=.{11,12}$)(?=\S* \S*$)0[ 1-9][ \d]+$/

See the regex demo

Details:

  • ^ - start of string
  • (?=.{11,12}$) - total length must be 11 to 12 chars (just a lookahead check, fails the match if the condition is not met)
  • (?=\S* \S*$) - there must be 1 space only (just a lookahead check, fails the match if the condition is not met)
  • 0 - the first char matched must be 0
  • [ 1-9] - the second char is any digit but 0 or space
  • [ \d]+ - 1 or more digits or spaces
  • $ - end of string.
like image 67
Wiktor Stribiżew Avatar answered Dec 25 '22 00:12

Wiktor Stribiżew


You can use this regex with positive lookahead:

/^0[1-9](?=\d* \d+$)[ \d]{9,11}$/

RegEx Demo

  • (?=\d* \d+$) ensures there is at least a space after first characters
  • Using {9,11} as 2 characters have already been matched at start (zero and non-zero)
like image 40
anubhava Avatar answered Dec 24 '22 23:12

anubhava