javascript 正则表达式只允许连字符和数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11899928/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:42:40  来源:igfitidea点击:

Regex to allow hypen & number only

javascriptjqueryregex

提问by Biki

I am using the RegEx ^[0-9]+$"to allow only digits. I want to allow hyphens -& spaces also.

我使用正则表达式^[0-9]+$"只允许数字。我也想允许连字符-和空格。

Can any one help me to modify the RegEx to a proper one?

任何人都可以帮助我将 RegEx 修改为正确的吗?

I was using following JS code to achieve the same, but in this way if the user is copying & pasting the text then the key press is not getting accounted.

我正在使用以下 JS 代码来实现相同的目的,但通过这种方式,如果用户正在复制和粘贴文本,则按键不会被计算在内。

//Allowed characters are : 8 = Back space,
//9 = Horizontal tab, 27 = esc, 127 = Delete,
//13 = Enter digits = 48 to 57, 45 = hypen

$('#PostalCode').keypress(function (e) {
    var key = (e.keyCode ? e.keyCode : e.which);
    return (key == 8 || key == 9 || key == 127 || key == 27 || key == 13 || key == 45 || (key >= 48 && key <= 57));
});

回答by Sebastian Paaske T?rholm

You can add a -and space in the character class like so:

您可以-在字符类中添加一个和空格,如下所示:

^[0-9 -]+$

Be sure to put the -either in the back or front (as it won't be mistaken for a range, then), or escape it:

一定要把 放在-后面或前面(因为它不会被误认为是一个范围,然后),或者逃避它:

^[0-9 \-]+$

You could also use \dinstead of 0-9, as they're equivalent:

您也可以使用\d代替0-9,因为它们是等效的:

^[\d -]+$

回答by diEcho

use ^[\d-\s]+$to allow hyphens also

使用^[\d-\s]+$允许连字符也