1

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.

1 Answer 1

3

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

/(<\s*?div\s*?id="#{my_id}"\s*?>.*?<\/div>)/im
Sign up to request clarification or add additional context in comments.

1 Comment

Well I'd accept this answer but people are downvoting my question like crazy so I'll just delete it. Not sure what's wrong with the question though. I'll leave this question open for 20 minutes so I can get feedback with what's wrong with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.