Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to replace parameters in a string

Tags:

regex

ruby

I am trying to iterate through elements of a struct, look for strings that include the format {...}, and replace them with a corresponding string from a hash. This is the data I'm using:

Request = Struct.new(:method, :url, :user, :password)
request = Request.new
request.user = "{user} {name}"
request.password = "{password}"
parameters = {"user" => "first", "name" => "last", "password" => "secret"}

This is attempt 1:

request.each do |value|
  value.gsub!(/{(.+?)}/, parameters["\1"])
end

In this attempt, parameters["\1"] == nil.

Attempt 2:

request.each do |value|
  value.scan(/{(.+?)}/) do |match|
    value.gsub!(/{(.+?)}/, parameters[match[0]])
  end
end

This results in request.user == "first first". Trying parameters[match] results in nil.

Can anyone assist solving this?

like image 375
Scotty Avatar asked Dec 15 '15 03:12

Scotty


People also ask

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.

How do I replace a character in a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does \f mean in regex?

Definition and Usage The \f metacharacter matches form feed characters.


1 Answers

Neither of your attempt will work because arguments of gsub! are evaluated prior to the call of gsub!. parameters[...] will be evaluated prior to replacement, so it has no way to reflect the match. In addition, "\1" will not be replaced by the first capture even if that string was the direct argument of gsub!. You need to escape the escape character like "\\1". To make it work, you need to give a block to gsub!.

But instead of doing that, try to use what already is there. You should use string format %{} and use symbols for the hash.

request.user = "%{user} %{name}"
request.password = "%{password}"
parameters = {user: "first", name: "last", password: "secret"}
request.each do |value|
  value.replace(value % parameters)
end
like image 146
sawa Avatar answered Oct 12 '22 11:10

sawa