问题
How can I define the -last vowel- in a string?
For example, I have a word "classic"
I want to find that the last vowel of the word "classsic" is the letter "i", and delete that last vowel.
I'm thinking :
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
回答1:
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"
回答2:
Like @aetherus pointed out: reverse the string, remove the first vowel then reverse it back:
str = "classic"
=> "classic"
str.reverse.sub(/[aeiou]/, "").reverse
=> "classc"
回答3:
regex = /[aeiou](?=[^aeiou]*\z)/
[aeiou]
matches one vowel[^aeiou]*
matches non-vowel characters 0 or more times\z
matches to the end of the string(?=...)
is positive forward looking and not including the match in the final result.
Here are a few examples:
"classic".sub(regex, '') #=> "classc"
"hello".sub(regex, '') #=> "hell"
"crypt".sub(regex, '') #=> "crypt
来源:https://stackoverflow.com/questions/39628583/how-do-i-remove-the-last-vowel-in-a-string-in-ruby