ruby正则表达式为什么不会停止循环

时间:2012-11-09 05:37:16

标签: ruby regex

这应该只匹配一个项目,但是当搜索空白时它会无限循环

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

1 个答案:

答案 0 :(得分: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