开发者

How to validate with regex that a string is OK as long as it contains 10 digits?

I'm processing input from a Web form. Basically, all I care about is that the value provided includes 10 digits, no more, no less.

These would be valid inputs:

1234567890
123 开发者_Go百科456 789 0 Hello!
My number is: 123456-7890 thanks

These would be invalid inputs:

123456789033 (too long)
123 Hello! (too short)
My number is one five zero nine thanks (no digits)

I've tried many different things with Regextester but it never matches correctly. I'm using the 'preg' setting (which is what I figured my CMS Typo3 uses) and my closest attempt is:

([0-9][^0-9]*){10}

which is kinda lame but is the closest I got.

Cheers!

EDIT: I cannot use any programming language to implement this. Imagine that I have a admin console field in front of me, in which I must enter a regular expression that will be used to validate the value. That's all the latitude I have. Cheers.


I think you've got the right idea. Maybe you can simplify it as (\d\D*){10}

If the regex has to match the complete string, you would want \D*(\d\D*){10}

UPDATE: It looks like you need ^\D*(\d\D*){10}$ to make sure you match the complete string.


A regular expression is not always the best tool for this kind of job. In this case it's probably easier and simpler to write a function to count the number of digits in a string. (Since you didn't mention a programming language, I'll use Python in my example.)

def count_digits(s):
    return len([x for x in s if x.isdigit()])

Then, you can use it like this:

s = "My number is: 123456-7890 thanks"
if count_digits(s) == 10:
    print("looks okay")
else:
    print("doesn't contain 10 digits")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜