I have the following patterns:
{remainingUsers, plural, =1 {# more agent} other {# more agents}}. Use the search to refine further.
Hello, Your friend {friend} is now online. {gender, select, female {She} male {He} other {They}}
And i'm trying to obtain what is inside the brackets. For the first one: "more agent" and "more agents" For the second one: "She", "He" and "They"
I'm trying to repeat a non capturing group and I ended up with the following regex:
.*\{.*(?:\{#?\s?(.*)\}) \}.*
But this only captures the last occurrence. For the first line it captures "more agents" and for the second one captures "They".
Can I solve this problem using only regex?
Thank you.
CodePudding user response:
Repeating capturing groups only capture the last matching occurence.
If you had to capture only what is inside brackets, a regex with g flag would have done the job.
But in your case, as you need to find occurences only within outer brackets, you will need to manually loop over matches.
If you know you may only have two levels of nested brackets (like in your example), you can easily first search for outer brackets:
/\{(([^{}]*|\{[^}]*\}) )\}/g
See it on your example.
Then, for every match (first group) of the regexp above, run /\{#?\s?([^}]*)\}/g to get what is inside inner brackets.
See it on your example.
CodePudding user response:
Assuing you are using a PCRE compliant rege engine, you can use
(?:\G(?!^)}|\{)[^{}]*{\K[^{}]*
See the regex demo. Details:
(?:\G(?!^)}|\{)- either the end of the previous match and then a}char (\G(?!^)}) or (|) a{char[^{}]*- zero or more chars other than{and}{- a{char\K- omit all matched so far[^{}]*- zero or more chars other than{and}.
