JBWyatt4 JBWyatt4 - 1 year ago 71
Ruby Question

Use a Regex to search for a keyword, extract a value next to keyword and replace keyword/value with a new substring reusing the value[Solved]

Using Ruby, in a string I want to extract somevalue and replace specialstring=somevalue in example string



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

Using somevalue to place between the .../ and .js

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

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