How to match full words and not substrings in Ruby

前端 未结 2 1830
有刺的猬
有刺的猬 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.

    0 讨论(0)
  • 2020-12-11 11:36
    \ba\b|\ban\b|\ball\b
    

    try this.this will look for word boundaries.

    0 讨论(0)
提交回复
热议问题