您的位置:首页 > 编程语言 > Ruby

Ruby remove substring matching to any element of array

2014-05-17 14:35 417 查看

Ruby remove substring matching to any element of array

I have a string say
str ="this is the string "
and i have an array of string say
array =["this is" ,"second element", "third element"]
I want to process the string such that sub string matching any of the element of array should be removed and rest of the string should be return.So i want the following output.
output: "the string "
How can i do this in ruby.solution 1:
str = "this is the string "
array = ["this is" ,"second element", "third element"]
pattern = /\b(?:#{ Regexp.union(array).source })\b/ # => /\b(?:this\ is|second\ element|third\ element)\b/

str[pattern] # => "this is"
str.gsub(pattern, '').squeeze(' ').strip # => "the string"
solution 2:
array =["this is" ,"second element", "third element"]str = "this is the string "str.gsub(Regexp.union(array),'') # => " the string "
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐