Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

regex - Repeated capturing group PCRE

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]+)()Kw+

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...