Repeated capturing group PCRE

后端 未结 1 860
悲&欢浪女
悲&欢浪女 2020-12-20 07:09

Can\'t get why this regex (regex101)

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

captures all the input, while this (regex101)

<
相关标签:
1条回答
  • 2020-12-20 07:14

    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.
    0 讨论(0)
提交回复
热议问题