Using regular expressions, how can I make sure there are nothing but zeroes after the first zero?
ABC1000000 - valid
3212130000 - valid
0000000000 - valid
ABC1000100 - invalid
0001000000 - invalid
The regex without validation would be something like this - [A-Z0-9]{10}
, making sure it is 10 characters.
CodePudding user response:
You could update the pattern to:
^(?=[A-Z0-9]{10}$)[A-Z1-9]*0 $
The pattern matches:
^
Start of string(?=[A-Z0-9]{10}$)
Positive looakhead, assert 10 allowed chars[A-Z1-9]*
Optionally match any char of[A-Z1-9]
0
Match 1 zeroes$
End of string
If a value without zeroes is also allowed, the last quantifier can be *
matching 0 or more times:
^(?=[A-Z0-9]{10}$)[A-Z1-9]*0*$
CodePudding user response:
You can use a lookahead to match a string of 10 characters. Then, just match everything but 0 from the start of the string, then only zeroes until the end of the string:
^(?=.{10}$)[^0]*0 $
This works for all of your test cases. You can change the one to many symbol after the last 0 to zero or many (*) if you don't require 0's.
var re = /^(?=.{10}$)[^0]*0 $/mi;
console.log(re.test('ABC1000000'));
console.log(re.test('3212130000'));
console.log(re.test('0000000000'));
console.log(re.test('ABC1001000'));
console.log(re.test('0001000000'));
console.log(re.test('32121300000')); // too short
console.log(re.test('321213000')); // too long
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
If you want to find strings like that within other text (rather than anchored with ^
and $
):
(?<![A-Z0-9])(?=[A-Z0-9]{10}(?:[^A-Z0-9]|$))([^0]*0*(?=(?:[^A-Z0-9]|$)))