简体   繁体   中英

Remove phrases in Array from string

I need to remove some phrases from a string in Ruby. The phrases are defined inside an array. It could look like this:

remove = ["Test", "Another One", "Something Else"]

Then I want to check and remove these from a given string.

"This is a Test" => "This is a " "This is Another One" => "This is " "This is Another Two" => "This is Another Two"

Using Ruby 1.9.3 and Rail 3.2.6.

ary = ["Test", "Another One", "Something Else", "(RegExp i\s escaped)"]
string.gsub(Regexp.union(ary), '')

Regexp.union can be used to compile an array of strings (or regexpes) into a single regexp which therefore only requires a single search & replace.

Regexp.union ['string', /regexp?/i] #=> /string|(?i-mx:regexp?)/

Simplest (but not most efficient):

# Non-mutating
cleaned = str
remove.each{ |s| cleaned = cleaned.gsub(s,'') }

# Mutating
remove.each{ |s| str.gsub!(s,'') }

More efficient (but less clear):

# Non-mutating
cleaned = str.gsub(Regexp.union(remove), '')

# Mutating
str.gsub!(Regexp.union(remove), '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM