I have the given strings:
bar"{foo}"bar
bar{foo}bar
I am trying to get both the first and third capture group to be just bar
. The second capture group should be {foo}
both with and without quotes for each match respectively.
I have the following regex:
(^.*)("?\{.*\}"?)(.*$)
With these results:
Match 1
Full match. bar"{foo}"bar
Group 1. bar"
Group 2. {foo}"
Group 3. bar
Match 2
Full match. bar{foo}bar
Group 1. bar
Group 2. {foo}
Group 3. bar
Why are the "
characters not both in the second group? I do not understand why it would be in the first if I am specifically calling it out in the second group. Do I need to tell the first group to ignore it or use it as a right bound?
As I was finishing writing this question I realized the problem I had. I needed to use a reluctant quantifier so the first group would not grab the "
before the next group had a shot.
Here is the small correction - I added .*?
(reluctant) instead of .*
(greedy):
(^.*?)("?\{.*\}"?)(.*$)
Good explanation here: Greedy vs. Reluctant vs. Possessive Quantifiers
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments