简体   繁体   中英

JavaScript regex to limit number of characters and allow digits and no more than one letter

I'm trying to make a regex that matches a string of digits and up to one letter (in any position), something like this:

^\d*[a-zA-Z]?\d*$

but the string must be between two and six characters long.

Eg these would be valid:

12  
a1  
12B3  
B12345  
123C45  
12345g 

but these would not be:

AB  
C123D 

Thanks in advance.

Your regex is fairly close, you just need to add a lookahead condition in your regex:

^(?=.{2,6}$)\d*[a-zA-Z]?\d*$

RegEx Demo

RegEx Details:

  • ^ : Start
  • (?=.{2,6}$) : Positive lookahead to assert that we have 2 to 6 characters ahead of start position
  • \d* : Match 0 or more digits
  • [a-zA-Z]? : Match an optional English letter
  • \d* : Match 0 or more digits
  • $ : End

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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