简体   繁体   中英

How to use gsub to remove . at the end of the string in ruby?

I need to remove all the special characters from the end of the string that sometimes will be there and sometimes not.

I have written this .gsub(/[,()'"]./,'') but it does not remove the . (full stop) from the string.

Can you tell me what is wrong in this?

You may use

.gsub(/[,()'".]+\z/,'')

The dot must be put inside the character class, the negated character class must be quantified with + (1 or more occurrences) and the \\z anchor should be added to assert the position at the end of the string.

See the Rubular demo .

Does it have to be .gsub ?

String#delete_suffix may be simpler.

my_string.delete_suffix '.'

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