[英]What is regex for alphanumeric with no spaces?
我需要这样匹配:
1. 1234 true
2. 1234 5678 false
3. 1234x true
4. x1234 true
5. abcd false
6. abcd 1234 false
所以我只需要匹配一个仅包含数字或仅包含数字和字符且没有空格(单个单词)的字符串。 这实际上不起作用:
/([0-9])\w+/g
您的模式([0-9])\w+
未锚定,因此它可以有部分匹配。
它还必须以数字开头,至少 1 个单词字符,字符串长度至少为 2 个字符。
您可以使用锚点,并确保匹配单个数字。 仅对于匹配,您可以省略捕获组:
^[^\W\d]*\d\w*$
^
字符串开始[^\W\d]*
可选择匹配除数字以外的任何单词字符\d
匹配单个数字\w*
匹配可选的单词字符$
字符串结尾注意\w
也可以匹配_
匹配整个字符串并需要至少一位数字:
/^[a-z]*[0-9][a-z0-9]*$/i
请参阅正则表达式证明。 重要: i
标志(不区分大小写)。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z', 'A' to 'Z' (0 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
[0-9] any character of: '0' to '9'
--------------------------------------------------------------------------------
[a-z0-9]* any character of: 'a' to 'z', 'A' to 'Z', '0' to '9'
(0 or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ the end of the string
const strings = ['1234','12x3', '12 X']; console.log(strings.filter(string=> string.match(/^[0-9a-z]+$/i)));
正则表达式: /^[0-9a-zA-Z]+$/
使用test
得到 boolean 结果; 使用match
获取匹配的字符串
const result = ['1234', '1234 5678', '1234x', 'x1234', 'abcd', 'abcd 1234'].map(str=> /^[0-9a-zA-Z]+$/.test(str)) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.