PCRE: Find matching brace for code block

☆樱花仙子☆ 提交于 2020-01-02 05:54:13

问题


Is there a way for PCRE regular expressions to count how many occurrences of a character it encounters (n), and to stop searching after it has found n occurrences of another character (specifically { and }).

This is to grab code blocks (which may or may not have code blocks nested inside them).

If it makes it simpler, the input will be a single-line string, with the only characters other than braces are digits, colons and commas. The input must pass the following criteria before code blocks are even attempted to be extracted:

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

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

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

Thanks, mniz.

Solution

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


回答1:


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

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

the other thing, i don't think this will be faster or less memory consuming than simple counter, especially on large strings.

and this is how to find all (valid) codeblocks in a string

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



回答2:


This is exactly what regular expressions are not good for. It's the classic example.

You should just iterate over the string character by character, and keep a count of the nesting level.




回答3:


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

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

$n=count($matches);



回答4:


It is impossible since the language you are describing is not a regular language.

Use a parser instead.



来源:https://stackoverflow.com/questions/2348547/pcre-find-matching-brace-for-code-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!