Need a regular expression - disallow all zeros

后端 未结 7 1506
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 14:41

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
相关标签:
7条回答
  • 2020-11-28 15:11

    You can use a (?!0+$) negative lookahead to avoid matching a string that only contains 1 or more zeros:

    /^(?!0+$)[A-Z0-9][0-9]{5}$/
      ^^^^^^^
    

    See the regex demo. This approach lets you just copy/paste the lookahead after ^ and not worry about how many chars the consuming part matches.

    Details

    • ^ - start of a string
    • (?!0+$) - a negative lookahead that fails the match if there are 1 or more 0 chars up to the end of the string ($)
    • [A-Z0-9] - an uppercase ASCII letter or a digit
    • [0-9]{5} - five digits
    • $ - end of string.
    0 讨论(0)
  • 2020-11-28 15:14

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

    /^(?!0{6})[A-Z0-9][0-9]{5}$/
    
    0 讨论(0)
  • 2020-11-28 15:14

    (?!000000)[A-Z0-9][0-9]{5} if lookahead is okay.

    0 讨论(0)
  • 2020-11-28 15:16

    I think this will do it. It checks for not 000000 and your original regex.

    (?!0{6})^[A-Z0-9][0-9]{5}$
    
    0 讨论(0)
  • 2020-11-28 15:25

    What if you checked for the all zeros case first and then, after determining that it's no all zeros apply your regex?

    if ( NOT ALL ZEROS)
        APPLY REGEX
    
    0 讨论(0)
  • 2020-11-28 15:26

    I would do two passes. One with your first regex, and one with a new regex looking for all zeros.

    0 讨论(0)
提交回复
热议问题