2014-09-19 92 views
1

完整的单词,而不是子这是我的代码如何匹配红宝石

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 

我想删除的话 - 一,一个和所有 但是,相反它匹配子也并删除它们

举一个例子输入 -

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 

正如你所看到的,它匹配了子字符串。

如何让它匹配单词而不是子字符串?

+0

更改单词列表,使它们不能位于单词的中间(例如“an”,“an。”) – 2014-09-19 02:58:29

回答

4

正则表达式中的|运算符的可能范围最广。您的原始正则表达式匹配\baanall\b

改变整个正则表达式:

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

或更改stopwordlist成一个正则表达式,而不是一个字符串。

stopwordlist = /a|an|all/ 

更好的是,您可能要使用Regexp.union

0
\ba\b|\ban\b|\ball\b 

试试这个。这个将会寻找字边界。