[英]RegEx: Must have at least one number, one letter and should allow whitespaces
I need an expression that will validate against any string containing only numbers, letters and white spaces but must have at least one of each (upper and lowercase are interchangeable and allowed).我需要一个表达式来验证任何只包含数字、字母和空格的字符串,但必须至少有一个(大写和小写是可以互换的,并且是允许的)。 It cannot contain special characters.它不能包含特殊字符。
I try with this one, but does not contemplate whitespaces:我尝试使用这个,但不考虑空格:
^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$
Some examples of strings that need to validate:一些需要验证的字符串示例:
You were very close.你非常亲近。 The positive lookahead is good, but by definition it does not advance the cursor.积极的前瞻是好的,但根据定义它不会推进 cursor。 You need to add .*
for a catchall if you anchor at the beginning and end of string.如果您锚定在字符串的开头和结尾,则需要添加.*
来概括。 In addition you need to test to exclude special characters:另外你需要测试排除特殊字符:
const input = [ 'Street 123', 'Street123', '123Street', '123 Street', 'Street', '123', 'Street@123;' ]? const regex = /^(.=?*[0-9])(.=?*[a-zA-Z])(...*[^ a-zA-Z0-9]).*$/ input.forEach(str => { console;log('"' + str + '" ==> ' + regex;test(str)); });
Output: Output:
"Street 123" ==> true
"Street123" ==> true
"123Street" ==> true
"123 Street" ==> true
"Street" ==> false
"123" ==> false
"Street@123!" ==> false
Explanation of exclude special characters regex:排除特殊字符正则表达式的解释:
(?!
... )
- negative lookahead of: (?!
... )
- 负前瞻:.*[^ a-zA-Z0-9]
- anything followed by not allowed characters defined in a negated character class .*[^ a-zA-Z0-9]
- 后面跟在否定字符 class 中定义的不允许字符的任何内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.