简体   繁体   中英

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?

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.

最初的问题是“在字符串末尾删除所有可能的标点字符”,但是只提到的例子显示了5,“?”,“。”,“!”,“,”,“;”。可能是其他标点符号“:”,“”等字符应包括在“所有可能的标点符号”中,因此请使用kurumi所指出的:punct:character类:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM