Ruby string.scan 问题

sevk · January 20, 2014 · Last by zw963 replied at January 22, 2014 · 3363 hits

想得到其中的"abcd" ,长度 4 .

s=  " sss\1\2abcd\xAA sss "
# 这里\1\2可能是\1\4  , 
# \1开头,\xAA结尾 , 长度4
# 我这样写:
s.scan(/\001[\002\004](.{4})\xAA/)[0]
#在ruby1.8里面可以正确执行,
#但1.9 2.0 报错了:
SyntaxError: (eval):2: invalid multibyte escape: /\001[\002\004](.{4})\xAA/

这里有啥好办法不? 数据是某硬件串口通讯的。

貌似,这种没有编码的正则匹配模式,在 1.9 之上,好像就不支持了?

" sss\1\2abcd\xAA sss ".force_encoding('ASCII-8BIT').scan(Regexp.new '\001[\002\004](.{4})\xAA', nil , 'n')[0] #if RUBY_VERSION >= "1.9"

#2 楼 @zhufenggood 学习了,多谢

刚刚问了下 Ri,

When the kcode parameter is `n' or `N' sets the regexp no encoding. It
means that the regexp is for binary strings.
You need to Sign in before reply, if you don't have an account, please Sign up first.