JBWyatt4 JBWyatt4 - 1 year ago 85
Ruby Question

Replace a keyword+value with a string infront and behind the value

Using Ruby, in a string I want to replace



<script src="https://gist.github.com/someuser/360256.js"></script>

I believe it can be done with a Regex (maybe gsub), but I am afraid I am just not that proficient.

Edit: "something... " indicates text that should not be changed. I want to replace all instances of


with the below in the string (extract the number)

<script src="https://gist.github.com/someuser/10000.js"></script>

Where 10000 can be any number terminated by a newline.

Answer Source
▶ input = %|something...
▷ specialstring=360256
▷ something...|
#⇒ "something...\nspecialstring=360256\nsomething..."
▶ out_tmpl = '<script src="https://gist.github.com/someuser/%{tmpl}.js"></script>'
▶ puts input.gsub(/^specialstring=(.*)$/) { out_tmpl % { tmpl: $1.strip }}
#⇒ something...
#  <script src=\"https://gist.github.com/someuser/360256.js\"></script>
#  something...

This is more-or-less generic solution, that parses input for occurrences of specialstring=ANYTHING, and then, using string formatting, injects this ANYTHING into the template, substituting the original pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download