简体   繁体   English

javascript正则表达式匹配单个或范围

[英]javascript regex match single or range

How can I match with regex (javascript) below two cases: 在以下两种情况下,我如何与正则表达式(javascript)匹配:

  • pattern case 1: any letter colon any 1 or 2 digits (ie A:1) 模式情况1:任何1或2位数字的冒号(即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) 模式案例2:任意字母冒号任意1或2位破折号任何字母:任意1或2位数字(即A:1-A:12)

I tried: ^([AZ]{1}:(\\d+)) which matches only first case 我试过了:^([AZ] {1}:(\\ d +))仅匹配第一种情况

Thanks 谢谢

This should work. 这应该工作。 It restricts the possible number of digits after the letter (1 or 2) and it also covers the second case: 它限制了字母(1或2)之后可能的数字位数,并且还涵盖了第二种情况:

^[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 正则表达式在线

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

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