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!
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]