正規表現の問題は、英語では、スペースが必要な単語に一致し、オプションで別の単語が続くが、別のスペースが必要であり、オプションで別の単語が必要であるということです。したがって、1つの単語は一致しませんが、単語の後に2つのスペースが続く場合は一致します。さらに、最後にスペースがある2つの単語も一致しますが、末尾にスペースがない場合はどちらも一致しません。
正確な正規表現を修正するには、文の最後の2番目の単語の周りに別のグループ(一致しないグループを)を追加し、このグループをオプションとして。を使用する必要があり(?:
ます。また、オプションのグループ内でも'を移動します。(
?
\s
これを試して:
^[a-zA-Z'-]+(?:\s[a-zA-Z'-]+(?:\s[a-zA-Z']+)?)?$
正規表現の説明:
^ # beginning of line
[a-zA-Z'-]+ # first matching word
(?: # start of second-matching word
\s[a-zA-Z'-]+ # space followed by matching word
(?: # start of third-matching word
\s[a-zA-Z']+ # space followed by matching word
)? # third-matching word is optional
)? # second-matching word is optional
$ # end of line
または、次の正規表現を試すこともできます。
^([a-zA-Z'-]+(?:\s[a-zA-Z'-]+){0,2})$
これにより、特定の行の1〜3語、つまり「都市」が一致し、新しい単語ごとに一致セットをさらに複製することなく、単語の範囲を調整できます。
正規表現の説明:
^( # start of line & matching group
[a-zA-Z'-]+ # required first matching word
(?: # start a non-matching group (required to "match", but not returned as an individual group)
\s # sub-group required to start with a space
[a-zA-Z'-]+ # sub-group matching word
){0,2} # sub-group can match 0 -> 2 times
)$ # end of matching group & line
したがって、3つ以上の単語に一致する機能を追加する場合は、上記2
の{0,2}
範囲で、一致させる単語の数から1を引いた数に変更できます(つまり、4つの単語に一致する場合は、に{0,3}
)。