Marko Avlijaš
Marko Avlijaš

Reputation: 1659

Ruby how to construct dynamic regexp?

I need to change html with ruby regexp.

This is regexp that works in rubular:

/(<\s*?div\s*?id="my_id"\s*?>.*?<\/div>)/im

I will resuse this code so I want to be able to change my_id part of regexp.

def extract_div_with_id(id)
  # str = somehow turn this regex into string
  str.sub!('my_id', id)
  regex = Regexp.new(str, Regexp::IGNORECASE | Regexp::MULTILINE)
  ...
end

How do I code first line of that function (one that is commented out)?

PS.
Nokogiri doesn't work. I don't know and don't care if it's because document is not valid and doctype is xhtml or because it contains php directives or whatever, I want to use regexp. Please don't tell me to use nokogiri or some non-regex solution.

Upvotes: 1

Views: 217

Answers (1)

mlovic
mlovic

Reputation: 864

You can use interpolation in the same way as with strings:

/(<\s*?div\s*?id="#{my_id}"\s*?>.*?<\/div>)/im

Upvotes: 3

Related Questions