最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - optional characters in javascript regular expression - Stack Overflow

programmeradmin4浏览0评论

I am trying to build a regular expression in javascript that checks for 3 word characters however 2 of them are are optional. 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

I am trying to build a regular expression in javascript that checks for 3 word characters however 2 of them are are optional. 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

Share Improve this question asked May 4, 2010 at 21:19 AnthonyAnthony 9233 gold badges23 silver badges35 bronze badges 2
  • Does /^\w\w?\w?$/i work for you? – tloflin Commented May 4, 2010 at 21:22
  • I did have to change it to \d and \Dbecause cause of the data i was testing but the answers were still correct about the optional characters – Anthony Commented May 6, 2010 at 22:58
Add a ment  | 

2 Answers 2

Reset to default 10

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. 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 _.

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. The $ forces the regex to match the entire string.

发布评论

评论列表(0)

  1. 暂无评论