Regular expression to match all but two consecutive braces

What will be the regular expression to match any but two consecutive curly braces ({)?
Example string:
{{some text}} string I want {{another set {{and inner}} }}
I want to get only string i want.

Using the stack to execute this stuff crossed my mind, but I wanted to know if this could be done using regular expression.
I am using PHP PCRE

Thanks in advance

+3
source share
2 answers

Use the lookahead expression (?!{{|}})to make sure you don't have a nested set of curly braces inside your outer set.

{{((?!{{|}}).)*}}

<?php
$string = '{{lot {{of}} characters}}';

for (;;)
{
    var_dump($string);
    $replacement = preg_replace('/{{((?!{{|}}).)*}}/', '', $string);

    if ($string == $replacement)
        break;

    $string = $replacement;
}

string(25) "{{lot {{of}} characters}}"
string(19) "{{lot  characters}}"
string(0) ""

, :

# Unbalanced braces.
string(23) "{{lot {{of}} characters"
string(17) "{{lot  characters"

string(23) "lot {{of}} characters}}"
string(17) "lot  characters}}"

# Multiple sets of braces.
string(25) "{{lot }}of{{ characters}}"
string(2) "of"

# Lone curlies.
string(41) "{{lot {{of {single curly} }} characters}}"
string(19) "{{lot  characters}}"
string(0) ""
+6

- , , , (? R).

$data = "{{abcde{{fg{{hi}}jk}}lm}}";
$regexp = "#\{\{((?:[^(\{\{)(\}\})]+|(?R))+)\}\}#";
$count = 0;

function revMatch($matches) {
  global $regexp, $count;

  if (is_array($matches)) {
    // Match detected, process for nested components
    $subData = preg_replace_callback($regexp, 'revMatch', $matches[1]);
  } else {
    // No match, leave text alone
    $subData = $matches;
  }

  // This numbers each match, to demonstrate call order
  return "(" . $count++ . ":<" . $subData . ">)";
}

echo preg_replace_callback($regexp, 'revMatch', $data);

: {{abcde{{fg{{hi}}jk}}lm}} (2:<abcde(1:<fg(0:<hi>)jk>)lm>)


regexp: #\{\{((?:[^(\{\{)(\}\})]+|(?R))+)\}\}#

, :

  • [^(\{\{)(\}\})]+

  • regexp. (?:) - .

NB. #s , , .

+2

Source: https://habr.com/ru/post/1781880/


All Articles