正则表达式匹配7到12位数字;可能包含空格或连字符 [英] Regular expression to match 7-12 digits; may contain space or hyphen

查看:615
本文介绍了正则表达式匹配7到12位数字;可能包含空格或连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在尝试解决PHP正则表达式问题,但我做不到.我需要编写一个正则表达式,它将匹配7到12位数字(0..9),并且可以选择在相邻数字之间使用单个连字符或单个空格.这就是我到目前为止所拥有的...

I have been trying to solve a PHP regular expression problem for awhile now but I just can't quite get it done. I need write a regex that will match between 7 and 12 digits (0..9) and there may optionally be either a single hyphen or a single space between adjacent digits. This is what I have so far...

$match1 = preg_match('/^\d[0-9\-\s]{5,10}\d$/', $number);
$match2 = preg_match('/(-\s|\s-|--|\s\s)/', $number);

如您所见,我必须使用两种不同的检查方式,但对我来说这还不够,因为我可以输入以下字符串:"1-2-3-4-5",但由于共有9个字符,它仍然可以通过应该失败,因为只有5位数字.

As you can see I have to use two different checks and it still isn't enough for me as I can input this string: "1-2-3-4-5" and it will still pass because there are a total of 9 characters but it should fail because there are only 5 digits.

在此问题上的任何帮助都将非常有用,谢谢!

Any help on the matter would be great, thanks!

推荐答案

怎么样:

/^(\d[-\s]?){6,11}\d$/

这篇关于正则表达式匹配7到12位数字;可能包含空格或连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆