Gah, regex is slightly confusing.
I'm trying to remove all possible punctuation characters at the end of a string:
if str[str.length-1] == '?' || str[str.length-1] == '.' || str[str.length-1] == '!' or str[str.length-1] == ',' || str[str.length-1] == ';'
str.chomp!
end
I'm sure there's a better way to do this. Any pointers?
str.sub!(/[?.!,;]?$/, '')
[?.!,;]
- Character class. Matches any of those 5 characters (note, .
is not special in a character class)?
- Previous character or group is optional$
- End of string.This basically replaces an optional punctuation character at the end of the string with the empty string. If the character there isn't punctuation, it's a no-op.
The original question stated 'Remove all possible punctuation characters at the end of a string," but the example only mentioned showed 5, "?", ".", "!", ",", ";". Presumably the other punctuation characters such as ":", '"', etc. should be included in "all possible punctuation characters," so use the :punct: character class as noted by kurumi:
str.sub!(/[[:punct:]]?$/,'')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With