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
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.
Just match for 4 digits (\d{4}
should do it) and then verify that your match is not equal to '0000'
.
Test for a sequence of 3 digits (0-9), then a 4th with only (1-9)
/\d{3}[1-9]/
(?<!\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
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.)