Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...