大佬教程收集整理的这篇文章主要介绍了Ruby 1.9:具有未知输入编码的正则表达式,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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:具有未知输入编码的正则表达式全部内容,希望文章能够帮你解决Ruby 1.9:具有未知输入编码的正则表达式所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。