简体   繁体   English

javascript正则表达式中的可选字符

[英]optional characters in javascript regular expression

I am trying to build a regular expression in javascript that checks for 3 word characters however 2 of them are are optional. 我试图在javascript中构建一个正则表达式来检查3个字符,但其中2个是可选的。 So I have: 所以我有:

/^\\w\\w\\w/i

what I am stumped on is how to make it that the user does not have to enter the last two letters but if they do they have to be letters 我难以理解的是如何使用户不必输入最后两个字母,但如果他们这样做,他们必须是字母

You can use this regular expression: 您可以使用此正则表达式:

/^\w{1,3}$/i

The quantifier {1,3} means to repeat the preceding expression ( \\w ) at least 1 and at most 3 times. 量词{1,3}意味着重复前面的表达式( \\w )至少1次,最多3次。 Additionally, $ marks the end of the string similar to ^ for the start of the string. 另外, $标记字符串的结尾类似于^作为字符串的开头。 Note that \\w does not just contain the characters az and their uppercase counterparts (so you don't need to use the i modifier to make the expression case insensitive) but also the digits 09 and the low line character _ . 请注意\\w不仅包含字符a - z及其大写对应项(因此您不需要使用i修饰符使表达式不区分大小写)而且还包含数字0 - 9和低位字符_

Like this: 像这样:

/^\w\w?\w?$/i

The ? ? marks the preceding expression as optional. 将前面的表达式标记为可选。

The $ is necessary to anchor the end of the regex. $是锚定正则表达式结束所必需的。
Without the $ , it would match a12 , because it would only match the first character. 如果没有$ ,它将匹配a12 ,因为它只匹配第一个字符。 The $ forces the regex to match the entire string. $强制正则表达式匹配整个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM