新手问题 还有中文变量的正则为什么容易经常带 “?-mix”

imwildcat · April 18, 2017 · Last by jasl replied at April 20, 2017 · 1704 hits

比如,

foo = '你好'
regex = /#{foo}/

会变成 `/?-mix:你好/`

而且最诡异的是,偶尔还能变成 `/你好/`

变量好像需要 escape。

Reply to pynix

如何 escape 呢?URI.escape 似乎不是 \uXXXX 的形式

Reply to jasl

主要是用中文字符串变量生成的正则表达式带这个 mix,然后匹配经常莫名其妙失败(重启一下 rails 就好了)。这个问题有什么解决思路吗?

Reply to imwildcat

你的 Ruby 版本是多少?是否方便试试升级到 2.4.1 (对正则引擎有了一些改动)

我用你的样本(MRI 2.4.1)没有复现出来的。

[1] pry(main)> foo = '你好'
=> "你好"
[2] pry(main)> regex = /#{foo}/
=> /你好/
[3] pry(main)> Regexp.new foo
=> /你好/

@jasl With your code

2.4.1 :008 > puts reg
(?-mix:你好)
 => nil

Regexp#to_s

Returns a string containing the regular expression and its options (using the (?opts:source) notation.

?-mix: are the options

When Regexp#to_s is called, especially when implicit, ?-mix turns out.

Reply to oth

sorry 我也没仔细去看 SO 的答案,这个我之前也没注意过的

You need to Sign in before reply, if you don't have an account, please Sign up first.