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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大