我有像“米勒德集团”和“烟囱公司”这样的公司名称。我想删除“集团”或“公司”之类的词,但前提是它们出现在词的最后。即,如果它们出现在中间某处,我不想删除它们。
我怎样才能在 Ruby 中做到这一点?gsub将从任何地方替换字符串,而且我有一个大约十个列表,所以我宁愿不运行gsub十次。如果我能提供一组这些词来删除,那就太好了。
尝试这样的事情:
['The Millard Group', 'The Chimney Corporation'].each do |s|
s.gsub!(/\ (Group|Corporation)$/, '')
end
您可以在正则表达式中添加更多要删除的单词,方法是在 more 之后添加它们|
因为并不是所有的事情都需要用 gsub 和 regexp 来解决:
endings = [' Group', ' Corporation']
corporations = ["The Millard Group", "The Chimney Corporation"]
corporations.each do |corp|
endings.each{|ending| corp.chomp!(ending)}
end
p corporations #=> ["The Millard", "The Chimney"]
编辑:也许这个版本可能会快一点?
corporations.map! do |corp|
last_word = (corp.rindex(' ')+1)..-1
corp.slice!(last_word) if endings.include?(corp[last_word])
corp.rstrip
end
使用以下约定:
\s对于空格/换行符等
$表示在行尾。
^表示在行首。
现在在您的正则表达式中使用它:
/\s*(Group|Corporation)$/
这将在您给定的末尾找到集团或公司String,并将其替换为您想要的任何内容。
'The Chimney Corporation'.gsub!(/\s*(Group|Corporation)$/,'')
#=>"The Chimney"
arr = [ "The Millard Group", "The Chimney Corporation", "The Ruby People" ]
BAD_WORDS = %w{ Group Corporation }
arr.reduce([]) do |a,s|
s.match( /(.*?)\s+(\w+)\s*$/ )
a << ( BAD_WORDS.include?($2) ? $1 : s )
end
# => ["The Millard", "The Chimney", "The Ruby People"]
arr.reduce([])创建一个在块内调用的空数组,a将可能修改的字符串插入其中。
s.match(/(.*?)\s+(\w+)\s*$/)有两个捕获组;第二个用于字符串的最后一个单词 ,(\w+)前面至少有一个空格字符\s+,第一个用于该空格之前的所有内容(.*?),?需要使其“非贪婪”。匹配结果存储在$1和中$2。
我们检查$2(字符串的最后一个单词s)是否包含在BAD_WORDS; 如果是我们追加$1到a,否则我们追加整个字符串s。
[编辑:我更喜欢迄今为止发布的其他解决方案,但为了多样性,我会留下这个。]