rails gsub,regexp ,match 的应用

阅读更多
1.将 电话号码的中的 '/' '+' 统一替换为 '-'
eg : "010/51248525+110"  --- "010-51248525-110"
domains = Global::Domain.all
domains.each do |domain|
  db_name = Entos::DbConfig.get(Rails.env,domain.orgnization_id)
  ActiveRecord::Base.connection.execute("USE #{db_name}")

  phone_regexp=/\A\d{3,4}-\d{7,8}\z|\A\d{3,4}-\d{7,8}-\d{1,3}\z|\A\d{3,15}\z|\A\d{7,8}-\d{1,3}\z/
  mobile_regexp=/\A\d{11}\z/
  qq_regexp=/\A\d{5,10}\z/
  User.find_each do |user|
    
    unless !user.phone.present?
    user.phone= user.phone.gsub(/\/|\+/,'-') 
    end
    if user.phone.present? and phone_regexp.match(user.phone).nil?
    user.phone=nil
    end
    if user.mobile_phone.present? and     mobile_regexp.match(user.mobile_phone).nil?
    user.mobile_phone=nil
    end
    if user.qq.present? and qq_regexp.match(user.qq).nil?
    user.qq=nil
    end
    user.save
  end
end




2.替换表情符号-- 将mblog 中【pinyin】替换为 【拼音】

emotions= {"hehe" => "[呵呵]",  "keai" => "[可爱]",  "qinqin" => "[亲亲]", "haha" => "[哈哈]", "xixi" => "[嘻嘻]", "yinxian" => "[阴险]",  "haixiu" => "[害羞]",
  "shuijiao" =>"[睡觉]",  "chanzui" => "[馋嘴]",  "huaxin" => "[花心]",  "ku" => "[酷]",  "jinqian" => "[金钱]",  "touxiao" => "[偷笑]",  "bishi" => "[鄙视]",
  "guzhang" => "[鼓掌]",  "sikao" => "[思考]",  "wabishi" => "[挖鼻屎]",  "baibai" => "[拜拜]",  "xu" => "[嘘]",  "weiqv" => "[委屈]",  "haqian" => "[哈欠]",
  "kelian" => "[可怜]",  "kaixin" => "[开心]",  "zhuakuang" => "[抓狂]",  "numa" => "[怒骂]",  "youhengheng" => "[右哼哼]",  "zuohengheng" => "[左哼哼]",  "yun" => "[晕]",
  "aini" => "[爱你]",  "liulei" => "[流泪]",  "shengbing" => "[生病]",  "shengqi" => "[生气]",  "heixian" => "[黑线]",  "heng" => "[哼]",  "yiwen" => "[疑问]",  "shuai" => "[衰]",
  "han" => "[汗]",  "shiwang" => "[失望]",  "kun"=> "[困]",  "tu"=> "[吐]",  "bulini" => "[不理你]",  "beishang" => "[悲伤]",  "bizui" => "[闭嘴]",  "chijing" => "[吃惊]",
  "xin" => "[心]",  "shangxin" => "[伤心]",  "dangao" => "[蛋糕]",  "lazhu" => "[蜡烛]",  "good" => "[good]",  "ok" => "[ok]",  "yeah" => "[耶]",  "zan" => "[赞]",
  "buyao" => "[不要]",  "lai" => "[来]",  "ruo" => "[弱]",  "zhutou" => "[猪头]",  "zhong" => "[钟]",  "huatong" => "[话筒]",  "geili" => "[给力]",  "v587" => "[威武]"}

domains = Global::Domain.all
domains.each do |domain|
  db_name = Entos::DbConfig.get(Rails.env,domain.orgnization_id)
  ActiveRecord::Base.connection.execute("USE #{db_name}")

  Mblog.find_each do |mblog|
    unless mblog.content.nil?
      mblog.content=mblog.content.gsub(/\[(\w+)\]/) do |c|
        emotions[$1]
      end
      mblog.save
    end
  end

end

你可能感兴趣的:(gsub,match,regexp,rails3)