为什么我的正则表达式将字符放在与我期望的不同的捕获组中?

Why is my regex putting a character in a different capture group than what I am expecting?

我有给定的字符串:

bar"{foo}"bar
bar{foo}bar

我试图让第一个和第三个捕获组都只是 bar。第二个捕获组应该是 {foo},每个匹配分别带有引号和不带引号。

我有以下正则表达式:

(^.*)("?\{.*\}"?)(.*$)

结果如下:

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

为什么 " 个角色不在第二组?我不明白为什么我要在第二组中明确指出它会出现在第一组中。我是否需要告诉第一组忽略它或将其用作右边界?

当我写完这个问题时,我意识到我遇到的问题。我需要使用一个不情愿的量词,这样第一组就不会在下一组拍摄之前抢到 "

这里是小修正 - 我添加了 .*?(不情愿)而不是 .*(贪婪):

(^.*?)("?\{.*\}"?)(.*$)

这里解释得很好:Greedy vs. Reluctant vs. Possessive Quantifiers