PCRE: find a suitable bracket for the code block

Is there a way for PCRE regular expressions to count the number of occurrences of the character it encounters (n) and stop searching after it has detected n occurrences of another character (in particular { and } ).

This is for capturing code blocks (which may or may not have code blocks nested within them).

If this simplifies, the input will be a one-line string, with the only characters other than curly braces being numbers, colons, and commas. The input must pass the following criteria before the code fragments are deleted:

 $regex = '%^(\\d|\\:|\\{|\\}|,)*$%'; 

All braces will have a matching pair and are correctly nested.

I would like to know if this can be achieved before I start writing a script to check every character in a string and count every occurrence of a bracket. Regular expressions will be much more memory friendly, as these strings can be several kilobytes in size!

Thanks, mniz.

Decision

PCRE: Lazy and Greedy at the same time (Possessive Quantifiers)

+4
source share
4 answers

pcre has recursive patterns , so you can do something like this

 $code_is_valid = preg_match('~^({ ( (?>[^{}]+) | (?1) )* })$~x', '{' . $code .'}'); 

Another thing, I don’t think it will be faster or less memory than a simple counter, especially on large lines.

and here's how to find all the (valid) code blocks in a string

 preg_match_all('~ { ( (?>[^{}]+) | (?R) )* } ~x', $input, $blocks); print_r($blocks); 
+4
source

This is exactly what ordinary expressions do not fit. This is a classic example.

You just have to iterate over the character of the string by character and keep the nesting count.

+4
source
 $regex='%^(\\d|\\:|\\{|\\}|,){0,25)$%'; preg_match($regex,$target,$matches); 

where: 25 in the first line indicates the maximum number of occurrences. then check:

 $n=count($matches); 
0
source

This is not possible since the language you are describing is not a common language .

Use a parser instead.

0
source

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


All Articles