duanboniao5903 2016-06-14 19:50
浏览 215
已采纳

具有两个连续(相同或不相同)匹配的正则表达式

I've written this regex for a PHP regex function:

\[\[.*?\]\]

This matches words or phrases between double square brackets. What I'm trying to find now is a regexp that match two or more consecutive (identical or not) matches. I've tried with

(\[\[.*?\]\]){2,}

and with this workaround: Regular Expression For Consecutive Duplicate Words. However, none of them worked. Does anyone has a better idea?

What I'm trying to match is, for example, [one][two][three]. The first part of the regexp will match [one] and I'm trying to get the entire phrase [one][two][three].

Thanks!

  • 写回答

1条回答 默认 最新

  • dtdvlazd56637 2016-06-15 13:45
    关注

    If you remove 1 bracket from both sides of your second pattern, it will already work. See (\[.*?\]){2,}.

    A more elegant solution is (?:\[[^][]*]){2,}. Here, \[ matches a [, [^][]* will match zero or more characters other than ] and [ and ] will match a closing literal ].

    If you want to capture the first [one] into Group 1, use (\[[^][]*])(?1)+. Here, (?1) re-uses Group 1 subpattern (i.e. \[[^][]*]).

    Here is a PHP demo:

    $re = '~(?:\[[^][]*]){2,}~'; 
    $str = "[one][two][three]"; 
    preg_match($re, $str, $matches);
    print_r($matches[0]); // => [one][two][three]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法