3

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!

Community
  • 1
  • 1
despinoUY
  • 43
  • 7
  • 8
    Try [`(\[\[.*?\]\])\1+`](https://regex101.com/r/oJ7bK1/1). Please provide test strings and expected outputs since the question sounds a bit unclear. How didn't it work? What do you mean by *identical or not matches*? – Wiktor Stribiżew Jun 14 '16 at 19:51
  • Maybe you need [`(\[\[.*?\]\])(?:\s*(?1))+`](https://regex101.com/r/oJ7bK1/3)? Or [`(?:\s*\[\[.*?\]\]){2,}`](https://regex101.com/r/oJ7bK1/4)? – Wiktor Stribiżew Jun 14 '16 at 20:00
  • @WiktorStribiżew 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]`. Is that clearer? Thank you! – despinoUY Jun 15 '16 at 13:37
  • So, your regex works, doesn't it? If you remove 1 bracket from both sides. See [`(\[.*?\]){2,}`](https://regex101.com/r/sP3hL5/1). Or a more elegant: [`(?:\[[^][]*]){2,}`](https://regex101.com/r/sP3hL5/2). Or do you want to capture the first `[one]`? Then use [`(\[[^][]*])(?1)+`](https://regex101.com/r/sP3hL5/3). What is the output *structure* you need? Does any of the above work for you? – Wiktor Stribiżew Jun 15 '16 at 13:39
  • @WiktorStribiżew My expected output is `[one][two][three]`. Sorry I'm not being clear enough! :( – despinoUY Jun 15 '16 at 13:46

1 Answers1

1

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]
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397