Regular Expression - 4 digits in a row, but can't be all zeros

前端 未结 5 1763
北荒
北荒 2021-01-04 02:31

I am looking for a solution that can exclusively be done with a regular expression. I know this would be easy with variables, substrings, etc.

And I am looking fo

相关标签:
5条回答
  • 2021-01-04 02:40

    Since I complained that the some of the answers here weren't regular expressions, I thought I'd best give you a regex answer. This is primitive, there's probably a better way, but it does work:

    ([1-9][0-9][0-9][0-9]|[0-9][1-9][0-9][0-9]|[0-9][0-9][1-9][0-9]|[0-9][0-9][0-9][1-9])
    

    This checks for something which contains 0-9 in each location, except one which must lie in 1-9, preventing 0000 from matching. You can probably write this simpler using \d instead of [0-9] if your regex parser supports that metacharacter.

    0 讨论(0)
  • 2021-01-04 02:45

    Just match for 4 digits (\d{4} should do it) and then verify that your match is not equal to '0000'.

    0 讨论(0)
  • 2021-01-04 02:51

    Test for a sequence of 3 digits (0-9), then a 4th with only (1-9)

    /\d{3}[1-9]/
    
    0 讨论(0)
  • 2021-01-04 02:54
     (?<!\d)(?!0000)\d{4}(?!\d)
    

    or, more kindly/maintainably/sanely:

    m{
         (?<! \d   )    # current point cannot follow a digit
         (?!  0000 )    # current point must not precede "0000"
         \d{4}          # match four digits at this point, provided...
         (?!  \d   )    # that they are not then followed by another digit
    }x
    
    0 讨论(0)
  • 2021-01-04 02:54

    Since PCRE supports lookarounds, \d{4}(?<!0000) will find any instance of four consecutive non-zero characters. See it in action here.

    If you must make sure the match only occurs in the correct position of the string, you can use ^.{X}\d{4}(?<!0000).{Y}$ instead, where X and Y are the number of preceding and following characters, respectively (12 and 5 in your example.)

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