javascript 如何使用正则表达式将固定长度的数字与中间的连字符匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5038428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a regular expression to match a fixed-length number with a hyphen in the middle?
提问by user622683
I am new to regular expressions and wanted to know how to write a regular expression that does the following:
我是正则表达式的新手,想知道如何编写执行以下操作的正则表达式:
Validates a string like 123-0123456789. Only numeric values and a hyphen should be allowed. Also, verify that there are 3 numeric chars before the hyphen and 10 chars after the hyphen.
验证像 123-0123456789 这样的字符串。只应允许使用数字值和连字符。此外,请验证连字符之前有 3 个数字字符,连字符后有 10 个字符。
回答by KooiInc
The given answers won't work for strings with more digits (like '012-0123456789876'), so you need:
给定的答案不适用于具有更多数字的字符串(如“012-0123456789876”),因此您需要:
str.match(/^\d{3}-\d{10}$/) != null;
or
或者
/^\d{3}-\d{10}$/.test(str);
回答by Joe
Try this:
试试这个:
^\d{3}-\d{10}$
This says: Accept only 3 digits, then a hyphen, then only 10 digits
这说:只接受 3 位数字,然后是连字符,然后是 10 位数字
回答by Jacob Relkin
Sure, this should work:
当然,这应该有效:
var valid = (str.match(/^\d{3}-\d{10}$/) != null);
Example:
例子:
> s = "102-1919103933";
"102-1919103933"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
true
> s = "28566945";
"28566945"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
false

