且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Ruby 中的字符串中删除所有非 ASCII 字符

更新时间:2023-02-21 15:59:43

您可以直接将您所询问的内容翻译成 Regexp.你写道:

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

我想去掉所有非 ASCII 字符

I want to get rid of all non ASCII characters

我们可以稍微改写一下:

We can rephrase that a little bit:

我想替换所有没有 ASCII 属性的字符

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

这是一个可以直接Regexp中表达的语句:

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

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

作为替代,您也可以使用 String#delete!:

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

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