zm10
zm10

Reputation: 227

Regex for two consecutive zero's at start of input

I need to write regex expression which can disallow inputs to have two consecutive zeros at the start of input

i've following regex rightnow /[^0-9]+/g there is one issue with this, as it allows as many zeros at the start of input which is wrong, ideally i would like something which can allow one zero at start if user enters zero first followed by any numbers but no more zero at start so valid input should be 0,1, 01,099,100,10000000 , 980980567000 etc invalid input 00,001,00100,00100000 , 000087990432 etc

Upvotes: 1

Views: 3681

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12668

Regexp matchers are good at saying what has to be matched, but it's a little trickie to tell a matcher what has not to be matched. To unmatch all strings beginning with 00 you have to match all strings that begin with different than 0 and all strings that, beginning with 0 don't continue with a 0 (being the empty string valid, as the string 0 doesn't begin with 00), so one such right expression could be:

^[^0].*$|^0([^0].*)?$

See demo for details.

Upvotes: 0

pixelarbeit
pixelarbeit

Reputation: 494

Matches invalid inputs: /^00\d*/

Matches valid inputs: /^(?!00)\d/*

^ stands for the beginning of the string
00 matches two consecutives zeros
(?!00) is a negative lookahead for two consecutive zeros
\d* matches any sequence of numbers

Upvotes: 6

tavnab
tavnab

Reputation: 2734

To match any static string at the beginning of a string (including "00"), you can use the ^ anchor.

To match strings starting with "00", your regex would be /^00/. If you want specifically numeric strings, /^00[0-9]*/.

Upvotes: 0

Related Questions