javascript 正则表达式字符串不以特殊字符开头或结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10031108/
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 String Doesn't Start or End With Special Character
提问by pixelbobby
SO buddies, greetings. I have some password requirements I need to implement and one of the requirements is the string cannot start or end with a special character. I did spend some time Googling around but my RegEx kung-fu is kimosabe level.
所以朋友们,问候。我有一些需要实现的密码要求,其中一项要求是字符串不能以特殊字符开头或结尾。我确实花了一些时间在谷歌上搜索,但我的 RegEx 功夫是 kimosabe 级别的。
Just in case you're interested in some code, here's the JavaScript:
Note: Yes, passwords are also validated on the server as well :) The following snippet runs the RegEx tests and simply checks or x's the row item associated with the password rule.
以防万一您对某些代码感兴趣,这里是JavaScript:
注意:是的,密码也在服务器上进行验证 :) 以下代码段运行 RegEx 测试并简单地检查或 x 是与密码规则关联的行项目.
var validate = function(password){
valid = true;
var validation = [
RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password),
RegExp(/[-!#$%^&*()_+|~=`{}\[\]:";'<>?,./]/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password),
!RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password),
!RegExp(/([a-z]|[0-9])/).test(password), (password.length > 7)
]
$.each(validation, function(i){
if(this == true)
$('.form table tr').eq(i+1).attr('class', 'check');
else{
$('.form table tr').eq(i+1).attr('class', '');
valid = false
}
});
return(valid);
}
回答by rgvcorley
EDIT:The regular expression you want is:-
编辑:您想要的正则表达式是:-
/^[a-zA-Z0-9](.*[a-zA-Z0-9])?$/
Additional information
附加信息
In regular expressions ^
means 'beginning of string' and $
means 'end of string', so for example:-
在正则表达式中^
意味着“字符串的开始”和$
“字符串的结尾”,例如:-
/^something$/
Matches
火柴
'something'
But not
但不是
'This is a string containing something and some other stuff'
You can negate characters using [^-char to negate-]
, so
您可以使用否定字符[^-char to negate-]
,所以
/^[^#&].*/
Matches any string that doesn't begin with a # or a &
匹配任何不以 # 或 & 开头的字符串
回答by gitaarik
This regex should be what you want:
这个正则表达式应该是你想要的:
/^[0-9a-z].*[0-9a-z]$/
回答by Thomas John
/^[a-zA-Z0-9](.*[a-zA-Z0-9])?$/
This expression checks the following validations:
此表达式检查以下验证:
- No blank spaces at start and end
- No special characters at the end and beginning
- special characters allowed in between
- 开头和结尾没有空格
- 结尾和开头没有特殊字符
- 中间允许的特殊字符