[英]regex for optional characters
I am using the following regex: 我使用以下正则表达式:
^([W|w][P|p]|[0-9]){8}$
The above regex accepts wp1234567
( wp
+7 digits) also. 上面的正则表达式也接受
wp1234567
( wp
+7位)。 Whereas expected: WP
+6digit or wp
+6digit or only 8 digit 预期:
WP
+ 6digit或wp
+ 6digit或仅8位数
For example: 例如:
WP123456
wp126456
64535353
Note that [W|w]
matches W
, w
and |
注意
[W|w]
匹配W
, w
和|
, since |
,自
|
inside a character class loses its special meaning of an alternation operator. 在一个字符类中失去了它对交替运算符的特殊含义。 Also, by setting the grouping
(...)
around [W|w][P|p]|[0-9]
you match 8 occurrences of *the whole sequences of WP
or digits. 此外,通过在
[W|w][P|p]|[0-9]
周围设置分组(...)
,您可以匹配WP
或数字的整个序列的8次出现。
You should set the correct value in the limited quantifier and remove grouping and use alternation to allow either wp
+6 digits or just 8 digits: 您应该在有限量词中设置正确的值并删除分组并使用交替以允许
wp
+6位数或仅8位数:
^(?:[Ww][Pp][0-9]{6}|[0-9]{8})$
The regex matches: 正则表达式匹配:
^
- start of string (not necessary if you check the whole string with String#matches()
) ^
- 字符串的开头(如果用String#matches()
检查整个字符串,则不需要) (?:[Ww][Pp][0-9]{6}|[0-9]{8})
- 2 alternatives: (?:[Ww][Pp][0-9]{6}|[0-9]{8})
- 2个替代方案:
[Ww][Pp][0-9]{6}
- W
or w
followed with P
or p
followed with 6 digits [Ww][Pp][0-9]{6}
- W
或w
后跟P
或p
后跟6位数 |
- or... [0-9]{8}
- exactly 8 digits [0-9]{8}
- 正好是8位数 $
- end of string $
- 结束字符串 Other scenarios (just in case): 其他场景(以防万一):
If you need to match strings consisting of 7 or 8 digits, you need to replace {8}
limited quantifier with {7,8}
: 如果您需要匹配由7或8位数字组成的字符串,则需要将
{8}
有限量词替换为{7,8}
:
^(?:[Ww][Pp][0-9]{6}|[0-9]{7,8})$
And in case you do not want to match Wp123456
or wP123456
, use one more alternation in the beginning: 如果您不想匹配
Wp123456
或wP123456
,请在开头再使用一次:
^(?:(?:WP|wp)[0-9]{6}|[0-9]{8})$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.