2

如何定义字符串中的 -last vowel-?

比如我有一个词“经典”

我想找到单词“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
4

3 回答 3

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" 
于 2016-09-22T01:37:40.703 回答
4

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

str = "classic"
=> "classic"
str.reverse.sub(/[aeiou]/, "").reverse
=> "classc"
于 2016-09-22T01:09:37.543 回答
1
regex = /[aeiou](?=[^aeiou]*\z)/
  • [aeiou]匹配一个元音

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

  • \z匹配到字符串的结尾

  • (?=...)是积极的前瞻性,不包括最终结果中的比赛。

这里有一些例子:

"classic".sub(regex, '') #=> "classc"
  "hello".sub(regex, '') #=> "hell"
  "crypt".sub(regex, '') #=> "crypt
于 2016-09-22T01:47:24.687 回答