Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a regular expression - disallow all zeros

Tags:

regex

I want to validate a string to meet the following conditions:

  • Must be 6 characters long
  • Only the first character can be alpha-numeric the rest must be numeric
  • If first digit is alpha, it must be caps
  • Can't be all zeros

I have the following regular expression that gets everything except the all zeros part. Is there a way to disallow all zeros?

^[A-Z0-9][0-9]{5}$

Is the only way to do this to check the regex (and allow "000000") but then check specifically that it's not "000000"?

Thanks.

like image 936
RHarris Avatar asked Mar 07 '12 21:03

RHarris


People also ask

How do you exclude a regular expression?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.

Is used for zero or more occurrences in regex?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.

How do I allow all items in regex?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.


1 Answers

Just have a negative lookahead like this to disallow all 0s:

/^(?!0{6})[A-Z0-9][0-9]{5}$/
like image 156
anubhava Avatar answered Sep 30 '22 13:09

anubhava