如何删除Ruby中字符串中的最后一个元音?

时间:2016-09-22 00:48:12

标签: ruby regex string remove-method

如何在字符串中定义-last元音?

例如,我有一个单词“classic”

我想找到“classs i c”这个词的最后一个元音是字母“ i ”,并删除最后一个元音。

我在想:

def vowel(str)
  result = ""
  new = str.split(" ")
  i = new.length - 1
  while i < new.length
    if new[i] == "aeiou"
      new[i].gsub(/aeiou/," ")
    elsif new[i] != "aeiou"
      i = -= 1
    end
  end
  return result
end

3 个答案:

答案 0 :(得分:13)

r = /
    .*      # match zero or more of any character, greedily
    \K      # discard everything matched so far
    [aeiou] # match a vowel
    /x      # free-spacing regex definition mode

"wheelie".sub(r,'') #=> "wheeli"
"though".sub(r,'')  #=> "thogh"
"why".sub(r,'')     #=> "why" 

答案 1 :(得分:4)

像@aetherus指出:反转字符串,删除第一个元音然后将其反转:

str = "classic"
=> "classic"
str.reverse.sub(/[aeiou]/, "").reverse
=> "classc"

答案 2 :(得分:1)

regex = /[aeiou](?=[^aeiou]*\z)/
  • [aeiou]匹配一个元音

  • [^aeiou]*匹配非元音字符0次或以上

  • \z匹配字符串的末尾

  • (?=...)积极向前看,不包括最终结果中的匹配。

以下是一些例子:

"classic".sub(regex, '') #=> "classc"
  "hello".sub(regex, '') #=> "hell"
  "crypt".sub(regex, '') #=> "crypt
相关问题