ケース1:タイトルのリストはそう(str[R] || "").rstrip #=> "".rstrip #=> ""
、最後の2つの例、str[R] => nil
のように、
titles = ["Dr.", "Prof.", "Mr.", "Mrs.", "Ms.", "Her Worship", "The Grand Poobah"] R =/ (?: # begin non-capture group #{Regexp.union(titles)} # "or" all the titles \s* # match >= 0 spaces )* # end non-capture group and perform >= 0 times /x # free-spacing regex definition mode #=>/ # (?: # begin non-capture group # (?-mix:Dr\.|Prof\.|Mr\.|Mrs\.|Ms\.|Her\ Worship|The\ Grand\ Poobah) # # "or" all the titles # \s* # match >= 0 spaces # )* # end non-capture group and perform >= 0 times # /x def extract_titles(str) t = str[R] || '' [str[t.size..-1], t.rstrip] end ["Prof. Dr. John J. Doe, Jr.", "Dr. Prin. Gloria Smith", "The Grand Poobah Dr. No", "Gloria Smith", "Cher, Ph.D."].each { |s| p extract_titles s } # ["John J. Doe, Jr.", "Prof. Dr."] # ["Prin. Gloria Smith", "Dr."] # ["No", "The Grand Poobah Dr."] # ["Gloria Smith", ""] # ["Cher, Ph.D.", ""]
何のタイトルがない場合
と仮定
を与えています。
どのように使用されているかは、クラスメソッドRegexp::unionのdocを参照してください。
ケース2:以下はすべてのタイトルが期間続く一の以上の小文字に続いて大文字、、で始まる単一の単語であることを前提としていたタイトル
のリストがありません。それが正しくない場合、下の正規表現はそれに応じて変更することができます。
このケースと以前のケースとの唯一の違いは、正規表現が変更されることです。
R =/
\A # match beginning of string
(?: # start a non-capture group
[A-Z] # match a capital letter
[a-z]+ # match > 0 lower-case letters
\.\s* # match a period followed by >= 0 spaces
)* # end non-capture group and execute >= 0 times
/x # free-spacing regex definition mode
["Prof. Dr. John J. Doe, Jr.", "Dr.Prin.Gloria Smith",
"Gloria Smith", "Cher, Ph.D."].each { |s| p extract_titles(s) }
# ["John J. Doe, Jr.", "Prof. Dr."]
# ["Gloria Smith", "Dr. Prin."]
# ["Gloria Smith", ""]
# ["Cher, Ph.D.", ""]
注:元の回答を簡略化しました。
"etc"でぼかしするだけではありません。あなたが関係する接頭辞が何であるかを明確に述べてください。 – sawa
@sawaできません。接頭辞のうち、すべてが言及することはできませんので、配列を考慮してください。 – Datt
あなたは言及できないものをどのように削除できますか? – sawa