まず、フリースペースモードでの正規表現は次のとおりです。
tidied = re.compile(r"""
( # $1: ...
( # $2: One ... from 3 alternatives.
13th # Either a1of3.
| ( # Or a2of3 $3: One ... from 2 alternatives.
Executive[ ] # Either a1of2.
| Residential # Or a2of2.
) # End $3: One ... from 2 alternatives.
| ( # Or a3of3 $4: Last match from 1 to 3 ...
(\w+) # $5: ...
[ ] #
){1,3} # End $4: Last match from 1 to 3 ...
) # End $2: One ... from 3 alternatives.
Floor #
) # End $1: ...
""", re.VERBOSE)
上記のパターンには、効果のない余分な括弧があることに注意してください。機能的に同等の単純化された式を次に示します。
tidied = re.compile(r"""
( # $1: One ... from 4 alternatives.
13th # Either a1of4.
| Executive[ ] # Or a2of4.
| Residential # Or a3of4.
| ( # Or a4of4 $2: Last match from 1 to 3 ...
(\w+) # $3: ...
[ ] #
){1,3} # End $2: Last match from 1 to 3 ...
) # End $1: One ... from 4 alternatives.
Floor #
""", re.VERBOSE)
最長の左端の一致
必要な単語の前に、事実上 4 つのグループ化された選択肢がありますFloor
。最初の 3 つの選択肢はそれぞれ 1 単語のみですが、4 番目の選択肢は 3 つの単語に一致します。NFA 正規表現エンジンは左から右に動作し、常に左端の最長の一致を見つけようとします。この場合、正規表現は一度に 1 文字ずつ正規表現を実行するため、各文字位置で 4 つのオプションすべてをテストします。4 番目のオプションは、他の 3 つの単語よりも 2 つ前の単語に常に一致する可能性があるため、常に最初に一致します (Floor
指定されたテキストの前に 3 つの単語があると仮定します)。の前に 3 つの単語がない場合Floor
、最初の 3 つの選択肢のいずれかが一致します。
13th
andの選択肢の後に必要なスペースがないことにも注意してくださいResidential
。したがって、連結されたテキストを含むテキストが提示された場合にのみ一致します: ResidentialFloor
or 13thFloor
.