ruby regex用于多个单词有条件匹配

Dat*_*att 3 ruby regex ruby-on-rails

我想删除所有名称前缀.(例如教授,博士,先生等),任何序列都可以超过一个.所以我想写一个正则表达式,slice所有这些前缀.我想这样做ruby.

以下是我想要实现的输入/输出设置.

"Prof. Dr. John Doe" => "John Doe"
"Dr. Prin. Gloria Smith" => "Gloria Smith"
"Dr. William" => "William"
"Sean Paul" => "Sean Paul"
Run Code Online (Sandbox Code Playgroud)

我还想将删除的前缀存储在另一个字符串中.

"Prof. Dr. John Doe" => "Prof. Dr."
"Dr. Prin. Gloria Smith" => "Dr. Prin."
"Dr. William" => "Dr."
"Sean Paul" => ""
Run Code Online (Sandbox Code Playgroud)

Car*_*and 6

案例1:给出了标题列表

假设

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.", ""]
Run Code Online (Sandbox Code Playgroud)

如果没有标题,如前两个例子那样str[R] => nil,那么(str[R] || "").rstrip #=> "".rstrip #=> "".

请参阅类方法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.", ""]
Run Code Online (Sandbox Code Playgroud)