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

时间:2009-12-21 19:37:28

标签: 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)

我目前的方法是在内部使用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">

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

2 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分:0)

按照此页面的建议:http://gnuu.org/2009/02/02/ruby-19-common-problems-pt-1-encoding/并添加

# encoding: utf-8

到你的rb文件的顶部。