gpt4 book ai didi

ruby 1.9 : Regular Expressions with unknown input encoding

转载 作者:数据小太阳 更新时间:2023-10-29 06:38:10 24 4
gpt4 key购买 nike

在输入编码未知的 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">

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

最佳答案

据我所知,没有更好的方法可以使用。但是,我可以建议稍微改动一下吗?

与其改变输入的编码,不如改变正则表达式的编码?每次遇到新编码时都翻译一个正则表达式字符串,这比翻译成百上千行输入以匹配正则表达式编码的工作要少得多。

# 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% 的情况下,对于数百或数千行的整个文件,编码是恒定的,这将导致重新编码的大量减少。

关于 ruby 1.9 : Regular Expressions with unknown input encoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1942148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com