是否有一种可接受的方法来处理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)
然而,这对我来说有点尴尬,我想问一下是否有更好的方法.