JBWyatt4 JBWyatt4 - 4 months ago 13
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

something...
specialstring=360256
something...


with

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


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
▶ 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.