字母数字、破折号和下划线但没有空格的正则表达式检查 JavaScript

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

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

javascriptregex

提问by Tom

Trying to check input against a regular expression.

尝试根据正则表达式检查输入。

The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.

该字段应只允许使用字母数字字符、破折号和下划线,不应允许使用空格。

However, the code below allows spaces.

但是,下面的代码允许使用空格。

What am I missing?

我错过了什么?

var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
    { alert('invalid'); }
else
    { alert('valid'); }

回答by Andy E

However, the code below allows spaces.

但是,下面的代码允许使用空格。

No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a +following the character class:

不,它没有。但是,它只会匹配长度为 1 的输入。对于长度大于或等于 1 的输入,您需要+以下字符类:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Note that neither the -(in this instance) nor the _need escaping.

请注意,-(在这种情况下)和都不_需要转义。

回答by sapht

You shouldn't use String.matchbut RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

如果您只对布尔值感兴趣,则不应使用 String.match而应使用RegExp.prototype.test(即/abc/.test("abcd"))而不是 String.search()。您还需要按照 Andy E 的回答中的说明重复您的角色类:

var regexp = /^[a-zA-Z0-9-_]+$/;

回答by Ivan Ivanov

Got stupid error. So post here, if anyone find it useful

有愚蠢的错误。所以在这里发布,如果有人觉得它有用

  1. -\._- means hyphen, dot and underscore
  2. \.-_- means all signs in range from dot to underscore
  1. -\._- 表示连字符、点和下划线
  2. \.-_- 表示从点到下划线的所有符号

回答by Grant Humphries

This syntax is a little more concise than the answers that have been posted to this point and achieves the same result:

此语法比到目前为止发布的答案更简洁,并获得相同的结果:

let regex = /^[\w-]+$/;

回答by Akash Yellappa

Try this

尝试这个

"[A-Za-z0-9_-]+"

Should allow underscores and hyphens

应该允许下划线和连字符

回答by David Fells

Don't escape the underscore. Might be causing some whackness.

不要转义下划线。可能会引起一些混乱。

回答by Santosh Shinde

try this one, it is working fine for me.

试试这个,它对我来说很好用。

"^([a-zA-Z])[a-zA-Z0-9-_]*$"