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

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

x = "foo

bar

baz" y = x.encode('UTF-16LE') re = /

(.*)/ x.match(re) => #<MatchData "

bar

" 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(/

(.*)/u) => #<MatchData "

bar

" 1:"bar">

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

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

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

 # 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>',line.encoding,16) # //u = 00010000 option bit set = 16 last_encoding = line.encoding end end line.match(regex)

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

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

 # encoding: utf-8 

到你的rb文件的顶部。