ここでは、2 つの問題が進行中です。グループを指定せずにgroup()を使用しましたが、明示的に括弧で囲まれたグループを使用した場合と括弧で囲まれたグループを使用しない場合の正規表現の動作の間で混乱していることがわかります。観察している括弧のないこの動作は、Python が提供する単なるショートカットであり、完全に理解するにはgroup()に関するドキュメントを読む必要があります。
>>> import re
>>> string = "baaa"
>>>
>>> # Here you're searching for one or more `a`s until the end of the line.
>>> pattern = re.search(r"a+$", string)
>>> pattern.group()
'aaa'
>>>
>>> # This means the same thing as above, since the presence of the `$`
>>> # cancels out any meaning that the `?` might have.
>>> pattern = re.search(r"a+?$", string)
>>> pattern.group()
'aaa'
>>>
>>> # Here you remove the `$`, so it matches the least amount of `a` it can.
>>> pattern = re.search(r"a+?", string)
>>> pattern.group()
'a'
要点は、文字列が1 つのピリオドにa+?
一致することです。a
ただし、は行末までa+?$
一致しa
ます。明示的なグループ化がなければ、 をまったく意味を持たせるのに苦労することに注意してください。とにかく、一般的には、何をグループ化するのかを括弧で明示する方がよいでしょう。明示的なグループの例を挙げましょう。?
>>> # This is close to the example pattern with `a+?$` and therefore `a+$`.
>>> # It matches `a`s until the end of the line. Again the `?` can't do anything.
>>> pattern = re.search(r"(a+?)$", string)
>>> pattern.group(1)
'aaa'
>>>
>>> # In order to get the `?` to work, you need something else in your pattern
>>> # and outside your group that can be matched that will allow the selection
>>> # of `a`s to be lazy. # In this case, the `.*` is greedy and will gobble up
>>> # everything that the lazy `a+?` doesn't want to.
>>> pattern = re.search(r"(a+?).*$", string)
>>> pattern.group(1)
'a'
編集:質問の古いバージョンに関連するテキストを削除しました。