如何在 Ruby 中匹配完整的单词而不是子字符串 [英] How to match full words and not substrings in Ruby
本文介绍了如何在 Ruby 中匹配完整的单词而不是子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码
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 和所有但是,它也匹配子字符串并删除它们
I wanted to remove words - a,an and all But, instead it matches substrings also and removes them
例如输入 -
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
如你所见,它匹配了子字符串.
As you can see, it matched the substring.
如何让它只匹配单词而不匹配子字符串?
How do I make it just match the word and not substrings ?
推荐答案
正则表达式中的 |
运算符采用了尽可能广泛的范围.您的原始正则表达式匹配 \ba
或 an
或 all\b
.
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/
或将 stopwordlist
改为正则表达式而不是字符串.
or change stopwordlist
into a regex instead of a string.
stopwordlist = /a|an|all/
更好的是,您可能想要使用 Regexp.union
.
Even better, you may want to use Regexp.union
.
这篇关于如何在 Ruby 中匹配完整的单词而不是子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文