Ruby 1.9:具有未知输入编码的正则表达式

Dat*_*ith 14 ruby regex encoding character-encoding

是否有一种可接受的方法来处理Ruby 1.9中的正则表达式,其输入的编码是未知的?假设我的输入恰好是UTF-16编码:

x  = "foo<p>bar</p>baz"
y  = x.encode('UTF-16LE')
re = /<p>(.*)<\/p>/

x.match(re) 
=> #<MatchData "<p>bar</p>" 1:"bar">

y.match(re)
Encoding::CompatibilityError: incompatible encoding regexp match (US-ASCII regexp with UTF-16LE string)
Run Code Online (Sandbox Code Playgroud)

我目前的方法是在内部使用UTF-8并在必要时重新编码(副本)输入:

if y.methods.include?(:encode)  # Ruby 1.8 compatibility
  if y.encoding.name != 'UTF-8'
    y = y.encode('UTF-8')
  end
end

y.match(/<p>(.*)<\/p>/u)
=> #<MatchData "<p>bar</p>" 1:"bar">
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说有点尴尬,我想问一下是否有更好的方法.

Myr*_*rys 9

据我所知,没有更好的方法可以使用.但是,我可以建议稍作修改吗?

而不是改变输入的编码,为什么不改变正则表达式的编码?每次遇到新编码时翻译一个正则表达式字符串比翻译数百或数千行输入以匹配正则表达式的编码要少得多.

# Utility function to make transcoding the regex simpler.
def get_regex(pattern, encoding='ASCII', options=0)
  Regexp.new(pattern.encode(encoding),options)
end



  # Inside code looping through lines of input.
  # The variables 'regex' and 'line_encoding' should be initialized previously, to
  # persist across loops.
  if line.methods.include?(:encoding)  # Ruby 1.8 compatibility
    if line.encoding != last_encoding
      regex = get_regex('<p>(.*)<\/p>',line.encoding,16) # //u = 00010000 option bit set = 16
      last_encoding = line.encoding
    end
  end
  line.match(regex)
Run Code Online (Sandbox Code Playgroud)

在病理情况下(输入编码改变每一行),这将同样缓慢,因为你每次通过循环重新编码正则表达式.但是在99.9%的情况下,编码对于数百或数千行的整个文件是恒定的,这将导致重新编码的大量减少.