Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I remove the last character from a string if it is a punctuation, in ruby?

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?

like image 492
oxo Avatar asked Apr 04 '11 16:04

oxo


2 Answers

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.

like image 87
Matthew Flaschen Avatar answered Sep 21 '22 22:09

Matthew Flaschen


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:]]?$/,'')
like image 34
Ray Baxter Avatar answered Sep 22 '22 22:09

Ray Baxter