JBWyatt4 JBWyatt4 - 11 months ago 27
Ruby Question

Use a Regex to search for a keyword, extract a value next to keyword and replace keyword/value with a new substring [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.

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.

Edit2: Changed title and above question to explain I wanted to extract a value and replace a substring with a different substring with value added.

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