开发者

How to check a String if it's an ASCII or not?

开发者 https://www.devze.com 2023-01-17 10:22 出处:网络
For example something like: \"ASCII\".is_asci开发者_StackOverflowi? # => true \"تجربة\".is_ascii? # => false

For example something like:

"ASCII".is_asci开发者_StackOverflowi? # => true

"تجربة".is_ascii? # => false


There is a bult-in Ruby string method right for you.

str.ascii_only? # → true or false

Returns true for a string which has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only?          #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?  #=> false


If your strings are Unicode (and they really should be, nowadays), you can simply check that all code points are 127 or less. The bottom 128 code points of Unicode are ASCII.

0

精彩评论

暂无评论...
验证码 换一张
取 消