2014-09-19 86 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 

試試這個。這個將會尋找字邊界。