用于匹配特定数字位数的正则表达式 [英] Regex for matching certain numbers of digits
问题描述
以下正则表达式将匹配 9-11 位数字:/\d{9,11}/
The following regex will match the range 9-11 digits: /\d{9,11}/
编写恰好匹配 9 或 11 位数字(不包括 10 位)的正则表达式的最佳方法是什么?
What is the best way to write a regex matching exactly 9 or 11 digits (excluding 10)?
使用输入元素的模式属性,因此正则表达式应该匹配输入字段的整个值.我想接受任何包含 9 位或 11 位数字的数字.
Using the pattern attribute of an input element, thus the regex should match the entire value of the input field. I want to accept any number containing 9 or 11 digits.
推荐答案
好吧,您可以尝试以下操作:
Well, you could try something like:
^\d{9}(\d{2})?$
这正好匹配九位数字,后跟可选的额外两位数字(即 9 位或 11 位数字).
This matches exactly nine digits followed by an optional extra-two-digits (i.e., 9 or 11 digits).
或者,
^(\d{9}|\d{11})$
也可以.
但请记住,并非所有都必须使用正则表达式来完成.检查字符串是否匹配 ^\d*$
并且字符串长度本身是 9 或 11(例如,使用诸如 strlen
之类的东西)可能同样容易.
But remember that not everything necessarily has to be done with regular expressions. It may be just as easy to check the string matches ^\d*$
and that the string length itself is either 9 or 11 (using something like strlen
, for example).
这篇关于用于匹配特定数字位数的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!