【发布时间】:2009-12-21 19:37:28
【问题描述】:
在 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">
但是,这对我来说有点尴尬,我想问一下是否有更好的方法。
【问题讨论】:
标签: ruby regex encoding character-encoding