How to match full words and not substrings in Ruby

前端 未结 2 1849
有刺的猬
有刺的猬 2020-12-11 11:00

This is my code

stopwordlist = \"a|an|all\"
File.open(\'0_9.txt\').each do |line|
line.downcase!
line.gsub!( /\\b#{stopwordlist}\\b/,\'\')
File.open(\'0_9_2.         


        
2条回答
  •  生来不讨喜
    2020-12-11 11:30

    The | operator in regex takes the widest scope possible. Your original regex matches either \ba or an or all\b.

    Change the whole regex to:

    /\b(?:#{stopwordlist})\b/
    

    or change stopwordlist into a regex instead of a string.

    stopwordlist = /a|an|all/
    

    Even better, you may want to use Regexp.union.

提交回复
热议问题