tags:

views:

376

answers:

3

Given an array of strings,

array1 = ["abcdwillbegoneabcccc","cdefwilbegokkkabcdc"]

and another array of strings which consist of patterns e.g. ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"]

the task is to remove substrings that match any of the pattern strings. for example a sample output for this case should be:

["willbegonea","wilbegokkk"]

because we have removed the substrings (prematch or postmatch as is appropriate depending on the position of occurrence) that matched one of the patterns. Assume that the one or two matches will always occur at the beginning or towards the end of each string in array1.

Any ideas of an elegant solution to the above in ruby?

+1  A: 

I think something like that should work :

def gimme_the_substring(string_to_test)
  ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"].each do |pattern|
    string_to_test.gsub!(/#{pattern}/,'')
  end
  return string_to_test
end

array1.map!{|s| gimme_the_substring(s)}
Yoann Le Touche
+2  A: 

I can see some potential gotchas here, in that if you change the order of the pattern strings, you could get a different result; and also, the second pattern might leave the string in a state that would have matched the first one, only it's too late now.

Assuming those are givens, I would go with Yoann's answer. The only way I can slightly improve it is to make the patterns regexen rather than strings, like this:

[/abcd/,/beg[o|p]n/,/bcc/,/cdef/,/h*gxwy/].each do |pattern|
    string_to_test.gsub!(pattern,'')
end

But of course if the patterns are coming from somewhere else, maybe they have to be strings.

Shadowfirebird
+3  A: 

How about building a single Regex?

array1 = ["abcdwillbegoneabcccc","cdefwilbegokkkabcdc"]

to_remove = ["abcd","beg[o|p]n","bcc","cdef","h*gxwy"]

reg = Regexp.new(to_remove.map{ |s| "(#{s})" }.join('|'))
#=> /(abcd)|(beg[o|p]n)|(bcc)|(cdef)|(h*gxwy)/

array1.map{ |s| s.gsub(reg, '') }
#=>  ["willeacc", "wilbegokkkc"]

Note that my result is different to your

["willbegonea","wilbegokkk"]

but I think mine's correct, it removes "abcd", "begon" and "bcc" from the original, which seems to be what's wanted.

Mike Woodhouse
and how can you easily get the co-ordinates of the resulting string in relation to the initial string using this approach.
eastafri
@George - I'm not sure I understand the question! Can you expand on it? What would you hope to see?
Mike Woodhouse
Is it also possible to know the match offsets? i.e. from what position to which position did the pattern match.
eastafri