简体   繁体   中英

Inserting a Variable into a String using Regex - Ruby

I'm having trouble inserting an outside variable into a string using regular expressions.

I have a string which looks like:

    string = "7  -"

And I want to insert a integer as a string into the space between the "7" and the "-", and I've tried to use interpolation, like so:

    variable = "15"
    string = string.gsub(/(\S?\d+)(\s)(\s)(\D)/, '\1\2#{variable}\3\4')

(the \\S? is to account for any " - " attached to a digit for whether it is positive or negative)

The output is a string looking like this:

    "7 \#{variable} -"

But I want the output to look like this:

    "7 15 -"

Here's an elegant solution to your problem:

s = "7  -"
v = 15
string = s.gsub(/\d\s/, "#{s.delete("-").strip} #{v}")
#=> "7 15 -"

Use double quote. Single-quoted string does not interpolate.

string = "7  -"
variable = "15"
string = string.gsub(/(\S?\d+)(\s)(\s)(\D)/, "\\1\\2#{variable}\\3\\4")
string # => "7 15 -"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM