简体   繁体   English

检测多个破折号

[英]Detect multiple dashes

I'm trying to validate Usernames with the following rules via RegExp : 我正在尝试通过RegExp使用以下规则验证用户名:

  1. Avoid leading and following dashes 避免领先和跟随破折号
  2. Avoid multiple dashes 避免多次破折号
  3. Update: It should allows only [a-z0-9-] also. 更新:它应该只允许[a-z0-9-]

So a username like -username , username- or user---name they should be all invalid, while a username like user-name or my-user-name should be still recognized as a valid username. 因此,像一个用户名-usernameusername-user---name他们应该是所有无效的,而像一个用户名user-namemy-user-name应仍然是公认有效的用户名。

Currently I'm doing that via two RegExp like this: jsFiddle 目前我通过两个RegExp这样做: jsFiddle

var a = new RegExp("^([^-][a-z0-9][a-z0-9-]+[a-z0-9][^-])$", "i");
var b = new RegExp("-[-]+", "i");
var username = "some-one";

if ( a.test(username) && !b.test(username) ) {
    alert(username.match(a)[1]);
} else {
    alert('error');
}

The above code works perfectly fine, however I'm wondering if there is any way to combine these two RegExp in one. 上面的代码完全正常,但我想知道是否有任何方法将这两个RegExp合二为一。 The reason is not neither performance nor cleaner code. 原因既不是性能也不是更清晰的代码。 I just want to improve my RegEx-ing skills as I've tried whatever I knew within the past few days, but with no success. 我只是想提高我的RegEx-ing技能,因为我在过去的几天里尝试过我所知道的一切,但没有成功。

Update 更新

Actually this ^([^-][a-z0-9][a-z0-9-]+[a-z0-9][^-])$ should be this ^([a-z0-9][a-z0-9-]+[a-z0-9])$ . 实际上这个^([^-][a-z0-9][a-z0-9-]+[a-z0-9][^-])$应该是这个^([a-z0-9][a-z0-9-]+[a-z0-9])$ I don't know why I put them there! 我不知道为什么我把它们放在那里! jsFiddle 的jsfiddle

Check it on http://jsfiddle.net/Vv7ma/1/ http://jsfiddle.net/Vv7ma/1/上查看

var a = new RegExp("(^-|[-]{2}|-$)", "i");
var username = "some-one";

if (! a.test(username)) {
    alert(username);
} else {
    alert('error');
}

If '-' in front, error. 如果前面有' - ',则错误。

If '-' in end, error. 如果' - '结尾,错误。

If '-' more than two in a row, error. 如果' - '连续两次以上,则错误。

Final answer on http://jsfiddle.net/Vv7ma/3/ which fulfill (It should allows only [a-z0-9-] also.) http://jsfiddle.net/Vv7ma/3/上完成的最终答案(它应该只允许[a-z0-9-]。)

var a = new RegExp("^([a-z0-9]+-)+[a-z0-9]+$", "i");
var username = "some-one";

if (a.test(username)) {
    alert(username);
} else {
    alert('error');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM