【问题标题】:How to match non-Unicode string with regexp in Ruby?如何在 Ruby 中将非 Unicode 字符串与正则表达式匹配?
【发布时间】:2020-02-12 07:09:43
【问题描述】:

我想匹配包含\xa0的字符串,比如:

"\xa0" =~ /\xa0/

但是会抛出错误:

SyntaxError: (eval):2: invalid multibyte escape: /\xa0/

我正在尝试使用 Unicode 来匹配:

"\xa0" =~ /\u00a0/

也会抛出错误:

ArgumentError: invalid byte sequence in UTF-8

那么,如何在 ruby​​ 中匹配 \xa0

【问题讨论】:

    标签: regex ruby ascii


    【解决方案1】:

    并非每个字节序列都是有效的 Unicode 字符串。 (或者更具体地说是 UTF-8)

    例如,您的单字节字符串不是:

    str = "\xa0"
    
    str.encoding        #=> #<Encoding:UTF-8>
    str.valid_encoding? #=> false
    str.codepoints      #   ArgumentError (invalid byte sequence in UTF-8)
    

    要处理任意字符串,您已将其编码设置为binary / ASCII:

    str = "\xa0".b      # <-- note the .b
    
    str.encoding        #=> #<Encoding:ASCII-8BIT>
    str.valid_encoding? #=> true
    str.codepoints      #=> [160]
    

    并将regexp encoding 设置为ASCII:(通过n 修饰符)

    str =~ /\xa0/n
    #=> 0
    

    【讨论】:

    • @TangMonk 因为字节 0x01 是 Unicode 中的有效代码点。
    猜你喜欢
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2014-12-15
    • 2019-05-01
    • 2013-10-18
    • 2012-11-26
    相关资源
    最近更新 更多