2016-04-25 56 views
1

感謝您的幫助! 我試圖在我的Rails應用中保存像Twitter標籤一樣的Twitter。用戶通過#hashtag符號輸入他們的標籤。但是,它一直保存空字符串。我添加了一個額外的除非聲明來打擊它,但現在它不保存任何標籤。 代碼:使用正則表達式保存Twitter Like Hashtags

def tag_list=(names) 
    self.tags = names.split(/\B#\w+/).map do |n| 
    unless n.strip == "" || n.strip == nil 
     Tag.where(name: n.strip).first_or_create! 
    end 
    end 
end 

我也試過以下的正則表達式也返回相同的:

/\B#\w+/ 

/(?:^|\s)(?:(?:#\d+?)|(#\w+?))\s/i 

/(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/i 
+0

['String#scan'](http://ruby-doc.org/core-2.3.0/String.html#method-i-scan)可能是比['String#split']更合適的工具(http://ruby-doc.org/core-2.3.0/String.h TML#方法-I-分割)。你並不是真的想將字符串拆分成幾塊,你試圖掃描字符串以找到某些模式。 –

回答

1

你的第一個正則表達式的工作原理完全,但必須使用scan代替split,所以你的代碼指定標籤是:

def tag_list=(names) 
    self.tags = names.scan(/\B#\w+/).map do |tag| 
    Tag.find_or_initialize_by(name: tag.remove('#')) 
    end 
    save! 
end 

的變化是:

  • 使用scan
  • 使用find_or_initialize_by代替where然後first_or_create!
  • 使用save!末,以節省一次
  • 如果要保存主題標籤與#前綴您可能不需要tag.remove('#')
+0

謝謝Hieu Pham - 完美的作品! – robinyapockets