开发者

Regex to allow 0 to 5 hyphens within a 10 - 15 numeric character string?

开发者 https://www.devze.com 2023-01-29 03:04 出处:网络
I\'m trying to create a regex for the following requirements: 10 numerical characters minimum 15 numerical characters maximum

I'm trying to create a regex for the following requirements:

  1. 10 numerical characters minimum
  2. 15 numerical characters maximum
  3. Allow 0 开发者_C百科to 5 hyphens, anywhere within string

I have this following regex, but it exceeds the 15 numerical character requirement if there aren't any hyphens:

/^([0-9]{10,15}|(?=[-]*)[0-9-]{11,19})$/

Thanks.


This regex will check for 0 to 5 hyphens and 10 to 15 digits. Any other characters are allowed.

^(?=[^-]*(-[^-]*){0,5}$)(?=\D*(\d\D*){10,15}$).*$

And this only allows digits and hyphens:

^(?=\d*(-\d*){0,5}$)(?=-*(\d-*){10,15}$).*$

Test it.


I'm pretty sure this can't be accomplished purely with one regex.

Here's an example using Python 2.6 without regular expressions (assumes input is only digits and hyphens):

input = "123-45678----9"
digitCount = len(input.translate(None, '-'))
hyphenCount = len(input.translate(None, '0123456789'))
if digitCount >= 0 and digitCount <= 15 and hyphenCount >= 0 and hyphenCount <= 5:
    print "Yay!"
0

精彩评论

暂无评论...
验证码 换一张
取 消