【发布时间】:2022-11-21 04:22:16
【问题描述】:
我正在尝试捕获 2 组数字,其中每组都是可选的,并且只有在包含数字时才应捕获。这是它应该匹配的所有有效组合的列表:
123(456)123(456)abc(456)-
123(efg)这些不是有效的组合,应该不是匹配:
abc(efg)abc-
(efg)
但是,我的正则表达式在
#4和#5组合上失败,即使它们包含数字。const list = ["123(456)", "123", "(456)", "abc(456)", "123(def)", "abc(def)", "abc", "(def)"]; const regex = /^(?:(\d+))?(?:\((\d+)\))?$/; list.map((a,i) => console.log(i+1+". ", a + "=>".padStart(11-a.length," "), (a.match(regex)||[]).slice(1).toString()));.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}所以,问题是为什么在一组后面使用
?时,如果没有匹配,它不会“跳过”该组?附言 使用此正则表达式,它还捕获
#4,但不捕获#5:/(?:^|(\d+)?)(?:\((\d+)\))?$/
【问题讨论】:
标签: javascript regex regex-group