gpt4 book ai didi

ruby - 内插正则表达式中 char 类的过早结束

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:26 27 4
gpt4 key购买 nike

我似乎无法解决这个问题,希望有人能提供帮助:

Nilfacs 是从散列中提取的字符串数组。

对于这一行:

looping_finaltext = finaltext.reject {|sentence| nilfacs.any? {|fac| sentence =~ /#{(fac)}/i}}

我收到以下错误:warning: character class has ']' without escape: /[[]]/block (2 levels) in <main>': premature end of char-class: /[[]]/i (RegexpError)

所有字符串都是普通单词(如“条件”),不包含需要转义的字符。

这是否表明一些未预料到的东西正在作为字符串输入到数组中?还是我这行的语法有问题?

最佳答案

Is this an indication that something unanticipated is being fed into the array as a string?

是的,就是这样。我希望您有嵌套数组,并且在其中某处有一个空数组 [[]] 的数组,其 to_s 表示会产生您找到的结果。

当您在正则表达式文字中使用插值时,源代码中的字符将被视为正则表达式中的字符。正如 /b[/ 不是一个有效的正则表达式,所以 foo="b["; bar=/#{foo}/ 无效。

nilfacs = [ "a[]", "b[", "c]", [[]] ]

nilfacs.each do |fac|
begin
p /#{fac}/
rescue RegexpError=>e
puts e
end
end

#=> empty char-class: /a[]/
#=> premature end of char-class: /b[/
#=> /c]/
#=> warning: regular expression has ']' without escape: /[[]]/
#=> premature end of char-class: /[[]]/

如果您想将字符串用作文字字符,则需要使用 Regexp.escape :

nilfacs.each do |fac|
p /#{Regexp.escape fac}/
end
#=> /a\[\]/
#=> /b\[/
#=> /c\]/

或者,您可能希望使用 Regexp.union 从您的数组中创建一个匹配其中所有文字字符串的正则表达式:

rejects = %w[dog cat]
re = Regexp.new(Regexp.union(rejects).source,'i') #=> /dog|cat/i
looping_finaltext = finaltext.reject{ |sentence| sentence=~re }

关于ruby - 内插正则表达式中 char 类的过早结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901122/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com