我有一个正则表达式:

regex = /(Si.ges[a-zA-Z\W]*avec\W*fonction\W*m.moires)/i

当我在一些(但不是所有)文本上使用它时,比如这篇:

text = "xation de 2 sièges-enfants sur la banquette AR),Pack \"Assistance\",Keyless Access avec alarme : Système de verrouillage/déverrouillage et de démarrage sans clé,Park Assist: Système d'assistance au stationnement en créneauet et en bataille,Rear Assist: Caméra de recul avec visualisation de la zone situ"

就像这样:text.match(regex),那么ruby就像是在一个无限循环中运行——但为什么呢?还有什么方法可以防止这种情况发生,比如让ruby抛出一个异常,而不使用Timeout,因为它与Sidekiq(https://github.com/mperham/sidekiq/wiki/Problems-and-Troubleshooting#add-timeouts-to-everything)一起使用时是一个已知的问题

ruby版本:2.7.2

推荐答案

Built-in character classes are more table-driven.
Given that, Negative built-in ones like \W, \S etc...
are difficult for engines to merge into a positive character class.

In this case, there are some obvious bugs because as you've said, it doesn't time out on
some target strings.

In fact, [a-xzA-XZ\W] works given the sample string. It times out when Y is included anywhere
but just for that particular string.

让我们看看能否确定这是否是一个bug.

首先,一些测试:

Test - Fail [a-zA-Z\W]

https://rextester.com/FHUQG84843

# Test - Fail  [a-zA-Z\W]
puts "Hello World!";
regex = /(Si.ges[a-zA-Z\W]*avec\W*fonction\W*m.moires)/ui;
text = "xation de 2 sièges-enfants sur la banquette AR),Pack \"Assistance\",Keyless Access avec alarme : Système de verrouillage/déverrouillage et de démarrage sans clé,Park Assist: Système d'assistance au stationnement en créneauet et en bataille,Rear Assist: Caméra de recul avec visualisation de la zone situ";
res = text.match(regex);
puts "Done";

Test - Pass [a-xzA-XZ\W]

https://rextester.com/RPV28606

Test - Pass [a-zA-Z\P{Word}]

https://rextester.com/DAMW9069


Conclusion: Report this as a BUG.
IMO this is a BUG with their built-in class \W which is engine defined,
since \P{Word} is a Unicode property defined function, not a range.
And we see that [a-zA-Z\P{Word}] works just fine.
Use \P{Word} inside classes as a temporary workaround.

In reality when modern-day engines were first designed, the logic of what
a negative class was [^] each item is AND NOT which when combined with a positive
class where each item is ORed results in errors in scope.
Perl had class errors still a short time ago.

Ruby相关问答推荐

Ruby插值法导致无序输出

Ruby PKCS7:添加;\r〃;字节正在 destruct 解密

为什么 rdoc 注释似乎以两个井号/井号符号开头?

根据部分已知值判断数组内容的简洁 Rubyist 方法是什么?

为什么 ruby​​ 获得证书信任链与 gnutls-cli 不同

哈希或其他对象的内存大小?

如何在 Ruby 的 RestClient gem 中设置超时?

Ruby 中的 class() 与 type()

如何在 VIM 中导航 Ruby 方法?

如何通过反射获取 Ruby 的 Module 类定义的常量?

Ruby 是否有任何数字格式化类?

`require': no such file to load in ruby

在 Ruby 中将多个代码块作为参数传递

Jekyll - 找不到命令

我应该如何在哈希上使用 each_with_object?

Ruby RVM apt-get 更新错误

获取类中声明的所有实例变量

Mountain Lion rvm 安装 1.8.7 x11 错误

使用 Ruby CSV 在导出的 CSV 中更改字段分隔符/分隔符

使用 Liquid 标记在 Jekyll 中获取今天的日期