How to remove all non - ASCII characters from a string in Ruby

后端 未结 3 957
小蘑菇
小蘑菇 2021-02-01 20:38

I seems to be a very simple and much needed method. I need to remove all non ASCII characters from a string. e.g © etc. See the following example.

#coding: utf-         


        
3条回答
  •  执念已碎
    2021-02-01 21:10

    You can just literally translate what you asked into a Regexp. You wrote:

    I want to get rid of all non ASCII characters

    We can rephrase that a little bit:

    I want to substitue all characters which don't thave the ASCII property with nothing

    And that's a statement that can be directly expressed in a Regexp:

    s.gsub!(/\P{ASCII}/, '')
    

    As an alternative, you could also use String#delete!:

    s.delete!("^\u{0000}-\u{007F}")
    

提交回复
热议问题