如何在 Ruby 中匹配整个单词而非子字符串

3
这是我的代码。
stopwordlist = "a|an|all"
File.open('0_9.txt').each do |line|
line.downcase!
line.gsub!( /\b#{stopwordlist}\b/,'')
File.open('0_9_2.txt', 'w') { |f| f.write(line) }
end

我希望删除a、an和all这些词,但实际上它也会匹配字串并将其删除。
例如输入:
Bromwell High is a cartoon comedy. It ran at the same time as some other programs about school life

我得到的输出是 -
bromwell high is  cartoon comedy. it r t the same time s some other programs bout school life

如您所见,它匹配了子字符串。

我该如何使其仅匹配单词而不是子字符串?


更改单词列表,使它们不能出现在单词中间(例如“an”,“an.”)。 - cubecubed
2个回答

7
正则表达式中的 | 运算符会尽可能地匹配更多内容。您原来的正则表达式匹配 \ba 或者 an 或者 all\b
请将整个正则表达式修改为:
/\b(?:#{stopwordlist})\b/

或者将stopwordlist更改为正则表达式而不是字符串。

stopwordlist = /a|an|all/

更好的方法是使用Regexp.union

1
\ba\b|\ban\b|\ball\b

尝试这个。它将寻找单词边界。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接