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.
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.
Share Improve this question edited May 24, 2016 at 10:42 Lotok asked May 24, 2016 at 10:39 LotokLotok 4,6071 gold badge37 silver badges46 bronze badges 2- Will the non-regex solution work for you? – gurvinder372 Commented May 24, 2016 at 10:41
- It is being used in a HTML5 pattern attribute so needs to be a regex – Lotok Commented May 24, 2016 at 10:42
3 Answers
Reset to default 15You 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 be0
[ 1-9]
- the second char is any digit but0
or space[ \d]+
- 1 or more digits or spaces$
- end of string.
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)
Here's my attempt. It's slightly faster than Wiktors. And since the time is already spent, I'll share it.
^(?=\d* \d*$)0[1-9 ][\d ]{9,10}$
See it here at regex101.