ruby - Premature end of char class in interpolated regex -
i can't seem solve issue, hope can help:
nilfacs array of strings pulled hash.
for line:
looping_finaltext = finaltext.reject {|sentence| nilfacs.any? {|fac| sentence =~ /#{(fac)}/i}} i following errors: warning: character class has ']' without escape: /[[]]/ , block (2 levels) in <main>': premature end of char-class: /[[]]/i (regexperror)
all of strings normal words (like "condition") , not contain characters should need escaped.
is indication unanticipated being fed array string? or there wrong syntax in line?
is indication unanticipated being fed array string?
yes, exactly. expect have nested arrays , somewhere in there have array of empty array [[]] to_s representation produces result found.
when use interpolation in regex literal characters in source treated in regex. /b[/ not valid regular expression, foo="b["; bar=/#{foo}/ not valid.
nilfacs = [ "a[]", "b[", "c]", [[]] ] nilfacs.each |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: /[[]]/ if want use strings literal characters, want use regexp.escape:
nilfacs.each |fac| p /#{regexp.escape fac}/ end #=> /a\[\]/ #=> /b\[/ #=> /c\]/ alternatively, may want use regexp.union create single regexp array matches literal strings therein:
rejects = %w[dog cat] re = regexp.new(regexp.union(rejects).source,'i') #=> /dog|cat/i looping_finaltext = finaltext.reject{ |sentence| sentence=~re }
Comments
Post a Comment