[英]What is regex for alphanumeric with no spaces?
I need to match this like:我需要这样匹配:
1. 1234 true
2. 1234 5678 false
3. 1234x true
4. x1234 true
5. abcd false
6. abcd 1234 false
so I need to match just a string with numbers only or numbers and characters only and with no spaces (single word).所以我只需要匹配一个仅包含数字或仅包含数字和字符且没有空格(单个单词)的字符串。 This doesn't really work:
这实际上不起作用:
/([0-9])\w+/g
Your pattern ([0-9])\w+
is unanchored, so it can have partial matches.您的模式
([0-9])\w+
未锚定,因此它可以有部分匹配。
It also has to start with a digit, and at least 1 word character, have the string to be at least 2 characters long.它还必须以数字开头,至少 1 个单词字符,字符串长度至少为 2 个字符。
You can use anchors, and make sure to match a single digit.您可以使用锚点,并确保匹配单个数字。 For a match only, you can omit the capture group:
仅对于匹配,您可以省略捕获组:
^[^\W\d]*\d\w*$
^
Start of string ^
字符串开始[^\W\d]*
Optionally match any word character except a digit [^\W\d]*
可选择匹配除数字以外的任何单词字符\d
Match a single digit \d
匹配单个数字\w*
Match optional word characters \w*
匹配可选的单词字符$
End of string $
字符串结尾Note that \w
can also match _
注意
\w
也可以匹配_
Match the entire string and require a at least one digit:匹配整个字符串并需要至少一位数字:
/^[a-z]*[0-9][a-z0-9]*$/i
See regex proof .请参阅正则表达式证明。 Important :
i
flag (case insensitive).重要:
i
标志(不区分大小写)。
EXPLANATION解释
--------------------------------------------------------------------------------
^ 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)));
regex: /^[0-9a-zA-Z]+$/
正则表达式:
/^[0-9a-zA-Z]+$/
use test
to get boolean result;使用
test
得到 boolean 结果; use match
to get matched string使用
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.