Ruby string.scan 问题

sevk · 2014年01月20日 · 最后由 zw963 回复于 2014年01月22日 · 3363 次阅读

想得到其中的"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"

刚刚问了下 Ri,

When the kcode parameter is `n' or `N' sets the regexp no encoding. It
means that the regexp is for binary strings.
需要 登录 后方可回复, 如果你还没有账号请 注册新账号