-1

これは1つのアイテムにのみ一致する必要がありますが、検索が空白の場合は無限にループし続けます

require 'optparse'
require 'json'
require 'pp'
require "base64"

data = 'a:92:{s:7:"key_one";s:0:"";s:7:"key_two";s:17:"http://localhost/";}'
key = "key_one"
search = ""
replace = "newstring"

num = 0
while matches = /(\"#{key}\")(\}|;)s:(\d+):\"#{search.gsub('/', '\/')}(.*?)\";/.match(data)
    full_match      = matches[0]
    the_key         = matches[1]
    start_char      = matches[2]
    characters      = matches[3]
    post_domain_str = matches[4]

    ### Debug
    num = num + 1
    puts the_key + "--" + start_char + "--" + characters + "--" + post_domain_str + "\n"
    ###

    replacement_string  = "#{the_key}#{start_char}s:#{characters.to_i + replace.length - search.length}:"

    if search == ""
        replacement_string << "\"#{replace}\";"
    else
        replacement_string << "\"#{replace}#{post_domain_str}\";"
    end

    data.gsub!(/#{Regexp.escape(full_match)}/, replacement_string)
end
4

1 に答える 1

1

これを試すことができますか:

require 'optparse'
require 'json'
require 'pp'
require "base64"

data = 'a:92:{s:7:"key_one";s:0:"";s:7:"key_two";s:17:"http://localhost/";}'
key = "key_one"
replace = "newstring"

def get_replaced_data(data, key, replace)
    key_str = data.match(/.*{(.*)}.*/)[1]
    ary = key_str.split(';')
    key_vals = []
    i = 0
    while i < ary.size
        key_vals << [ary[i], ary[i+1]]
        i += 2
    end
    replace_data = "s:#{replace.size}:\"#{replace}\""
    key_vals.each do |dat|
        data_key = dat[0].match(/.*\"(.*)\".*/)[1]
        dat[1] = replace_data if data_key == key
    end
    result_str =key_vals.join(';')
    data.gsub(/\{.*\}/, '{'+result_str+'}')
end

data_r = get_replaced_data(data, key, replace)
# puts data_r
于 2012-11-09T06:38:37.373 に答える