Repeated capturing group PCRE

喜你入骨 提交于 2019-11-28 13:21:36

问题


Can't get why this regex (regex101)

/[\|]?([a-z0-9A-Z]+)(?:[\(]?[,][\)]?)?[\|]?/g

captures all the input, while this (regex101)

/[\|]+([a-z0-9A-Z]+)(?:[\(]?[,][\)]?)?[\|]?/g

captures only |Func

Input string is |Func(param1, param2, param32, param54, param293, par13am, param)|

Also how can i match repeated capturing group in normal way? E.g. i have regex

/\(\(\s*([a-z\_]+){1}(?:\s+\,\s+(\d+)*)*\s*\)\)/gui

And input string is (( string , 1 , 2 )).

Regex101 says "a repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations...". I've tried to follow this tip, but it didn't helped me.


回答1:


Your /[\|]+([a-z0-9A-Z]+)(?:[\(]?[,][\)]?)?[\|]?/g regex does not match because you did not define a pattern to match the words inside parentheses. You might fix it as \|+([a-z0-9A-Z]+)(?:\(?(\w+(?:\s*,\s*\w+)*)\)?)?\|?, but all the values inside parentheses would be matched into one single group that you would have to split later.

It is not possible to get an arbitrary number of captures with a PCRE regex, as in case of repeated captures only the last captured value is stored in the group buffer.

What you may do is get mutliple matches with preg_match_all capturing the initial delimiter.

So, to match the second string, you may use

(?:\G(?!\A)\s*,\s*|\|+([a-z0-9A-Z]+)\()\K\w+

See the regex demo.

Details:

  • (?:\G(?!\A)\s*,\s*|\|+([a-z0-9A-Z]+)\() - either the end of the previous match (\G(?!\A)) and a comma enclosed with 0+ whitespaces (\s*,\s*), or 1+ | symbols (\|+), followed with 1+ alphanumeric chars (captured into Group 1, ([a-z0-9A-Z]+)) and a ( symbol (\()
  • \K - omit the text matched so far
  • \w+ - 1+ word chars.


来源:https://stackoverflow.com/questions/41582889/repeated-capturing-group-pcre

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