简体   繁体   中英

javascript regex match single or range

How can I match with regex (javascript) below two cases:

  • pattern case 1: any letter colon any 1 or 2 digits (ie A:1)
  • pattern case 2: any letter colon any 1 or 2 digits dash any letter:any 1 or 2 digits (ie A:1-A:12)

I tried: ^([AZ]{1}:(\\d+)) which matches only first case

Thanks

This should work. It restricts the possible number of digits after the letter (1 or 2) and it also covers the second case:

^[A-Z]:\d{1,2}(-[A-Z]:(\d{1,2}))?$

You may use this regex t make 2nd part an optional match:

/^[a-zA-Z]:\d{1,2}(?:-[a-zA-Z]:\d{1,2})?$/gm

RegEx Demo

Uses Positive lookahead = (?=...)

^([A-Z]{1}\:\d{1,2}(\-(?=[A-Z]{1}:\d{1,2}))?)+$

Regex Online

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