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:]]?$/,'')
all non-word characters.
text.gsub(/\W$/, "")
what this does is does is looks at the string, finds the punctuation at the end, and globally substitutes with nothing = thus removing it.
This really does work, and it's a ruby way to use regex.
You should be able to use a regular expression to do this. I don't have any experience with ruby, but here's a RegEx that should work:
/(.*)[^\w\d]?$/
You can use backreference #1 to get the string without the last punctuation character.
mystring.gsub(/[[:punct:]]+$/,"")
Without using the empty string:
str = /[?.!,;]?\z/.match(str).pre_match
or in the other order
str = str.match(/[?.!,;]?\z/).pre_match
str.chomp!
won't do anything in this case. You'd have to do str.chop!
精彩评论