【问题标题】:Match string with last part different匹配字符串与最后一部分不同
【发布时间】:2016-05-26 19:48:26
【问题描述】:

我有以下正则表达式:

/{{trans-template-id:(\d)+}}/i

它与{{trans-template-id:7}} 完美匹配。

但是,我想对其进行修改,使其也与{{trans-template-hash:asdf1234}} 匹配。我将如何修改它?

我已经做到了这一点,但我似乎对正则表达式还不够了解:

/{{trans-template-(id:(\d)+|hash:[a-zA-Z0-9]+)}}/i

【问题讨论】:

  • /{{trans-template-(id:(\d)+|hash:[a-zA-Z0-9]+)}}/i 应该有什么问题
  • 根据this 不匹配
  • 啊这是因为我没有g(全局)标志

标签: php regex


【解决方案1】:

如果你想做一个公共组,你可以使用

{{trans-template-(id|hash):((?<=id:)\d+|(?<=hash:)\w+)}}

Regex Demo

您也可以使用 branch reset 之类的

{{trans-template-(?|id:(\d+)|hash:(\w+))}}

Regex Demo

【讨论】:

  • trans-template-id: 后面必须跟 integer。第一个不会让string 值漏掉吗?
  • 链接完美运行。不知道您是否想将其添加为答案
  • @Albert 我已经添加了另一个......这会更好,因为它不会有任何空的捕获组
  • 不要使用这些丑陋的lookbehinds,您应该使用分支重置功能(?|...(...)...|...(...)...) (每个分支的捕获组具有相同的编号)构建您的模式
  • @CasimiretHippolyte 太棒了..我有很多要读的东西..我知道这份工作会有一些东西..谢谢
猜你喜欢
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
相关资源
最近更新 更多