dongzhi2332 2012-04-16 13:41
浏览 95
已采纳

正则表达式捕获组流入第二个匹配集

I am trying to match multiple inputs in the same regex to capture the number following.
If the input doesnt match the first group then I have issues because all previous capture groups are still captured despite it doesnt match they group. I believe I need to use a lookaround assertion, but I am not familiar with those.

Sample input:

wordA 123456
wordA: 123456
wordA : 123456
wordA R123465
wordA: R123456
wordA : R123456
wordB R123465

WordA has both optional : and R. So far I have this: /(?:wordA :?R?(\d+)|wordB R(\d+))/i.
Using the last sample input provides this result:

array
  0 => string 'wordB R123456' (length=13)
  1 => string '' (length=0)
  2 => string '123456' (length=6)

Wanted result is:

array
  0 => string 'wordB R123465' (length=13)
  1 => string '123456' (length=6)

Any ideas how to fix ?

  • 写回答

2条回答 默认 最新

  • du9826 2012-04-16 13:50
    关注

    The problem is your alternation

    /(?:wordA :?R?(\d+)|wordB R(\d+))/i
                  ^^^^^        ^^^^^
                 Group 1       Group 2
    

    So if your regex matches the second alternative, the result will be in group 2 (array[2]) and the first group will be empty.

    Change it to this

    (?:wordA :?R?|wordB R)(\d+)
    

    See it here on Regexr

    Then your number will always be in the first group (because there is only one)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序