“结合" 2正则表达式与逻辑还是? [英] “combine” 2 regex with a logic or?
问题描述
我有两种javascript模式:
I have two patterns for javascript:
/^ [A-z0-9] {10} $/
-长度为10个字母数字符号的字符串.
/^[A-z0-9]{10}$/
- string of exactly length of 10 of alphanumeric symbols.
和
/^ \ d + $/
-至少长度为1的任意数量.
/^\d+$/
- any number of at least length of one.
10 或任意数字的 OR 字符串如何表达?
How to make the expression of OR string of 10 or any number?
var模式=/^([A-z0-9] {10})|(\ d +)$/;
由于某种原因无法正常工作.至少可以通过
doesn't work by some reason. It passes at lest
pattern.test("123kjhkjhkj33f"); // true
这不是数字,也不是 A-z0-9
字符串的10个长度.
which is not number and not of length of 10 for A-z0-9
string.
推荐答案
请注意,您的 ^([A-z0-9] {10})|(\ d +)$
模式匹配10个字符在字符串开头的 A-z0-9
范围内( ^
仅修改([A-z0-9] {10})
部分(第一个替代分支),或(< |
)在带有(\ d +)$
($
仅修改(\ d +)
分支模式.
Note that your ^([A-z0-9]{10})|(\d+)$
pattern matches 10 chars from the A-z0-9
ranges at the start of the string (the ^
only modifies the ([A-z0-9]{10})
part (the first alternative branch), or (|
) 1 or more digits at the end of the stirng with (\d+)$
(the $
only modifies the (\d+)
branch pattern.
还请注意, Az
是一个错字, [Az]
确实会不仅匹配ASCII字母.
Also note that the A-z
is a typo, [A-z]
does not only match ASCII letters.
您需要按如下方式修复它:
You need to fix it as follows:
var pattern = /^(?:[A-Za-z0-9]{10}|\d+)$/;
或使用 i
修饰符:
var pattern = /^(?:[a-z0-9]{10}|\d+)$/i;
请参见 正则表达式演示 .
请注意,分组在这里很重要:(?:... | ...)
使锚点适当地应用于每个锚点.
Note that grouping is important here: the (?:...|...)
makes the anchors apply to each of them appropriately.
详细信息
-
^
-字符串的开头 -
(?:
-一个非捕获交替组:-
[A-Za-z0-9] {10}
-10个字母数字字符 -
|
-或 \d+
- 1 位或更多位
^
- start of string(?:
- a non-capturing alternation group:[A-Za-z0-9]{10}
- 10 alphanumeric chars|
- or\d+
- 1 or more digits
这篇关于“结合" 2正则表达式与逻辑还是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-