Javascript 正则表达式允许数字、加号、减号和括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30618955/
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
Regex to allow numbers, plus symbol, minus symbol and brackets
提问by user2847098
I am trying to create a regex that allows only the following 0-9, plus symbol, minus symbol and brackets (). No limitations on length of each of the mentioned. So far I have this but it does not seem to work.
我正在尝试创建一个仅允许以下 0-9、加号、减号和方括号 () 的正则表达式。对每个提到的长度没有限制。到目前为止,我有这个,但它似乎不起作用。
/^[0-9 -+]+$/
回答by panther
Hyphen -has to be at the end of charlist, else it means interval.
连字符-必须在字符列表的末尾,否则表示间隔。
/^[0-9 ()+-]+$/
0-9 is possible to write shortly as \d
0-9 可以简写为 \d
/^[\d ()+-]+$/
回答by emartinelli
This should work for you:
这应该适合你:
^[\d\(\)\-+]+$
^-> start of string
^-> 字符串开头
\d-> same as [0-9]
\d-> 与 [0-9] 相同
+-> one or more repetitions
+-> 一次或多次重复
$-> end of string
$-> 字符串结束
var re = /^[\d\(\)\-+]+$/m;
var str = ['09+()1213+-','fa(-ds'];
var m;
var result = "";
for(var i = 0; i < str.length; i++) {
if ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
result += "\""+str[i]+ "\"" + " is matched:" + (m != null) + "</br>";
}
document.getElementById("results").innerHTML = result
<div id="results"></div>
回答by Andie2302
To match digits, +, -, (, and ) use:
要匹配数字、+、-、( 和 ),请使用:
[+()\d-]+
The trick is the position of the characters inside the character class.
诀窍是字符类中字符的位置。
if (/^[+()\d-]+$/.test(text)) {
} else {
}
回答by MortenMoulder
[\d\(\)\+\-\(\)]
That should do it.
应该这样做。
EDIT: But since some agree the escaping is too much, here ya go:
编辑:但由于有些人同意转义太多,所以你去:
[\d+()-]



