开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜