2010-12-18 18 views
0

好的。這很晚了,我很累。Rails中的簡單正則表達式問題

我想匹配字符串中的字符。具體來說就是'a'的出現。就像「一個半」一樣。

如果我有一個全是小寫的字符串。

"one and a half is always good" # what a dumb example. No idea how I thought of that. 

我呼籲它

"one and a half is always good".titleize #=> "One And A Half Is Always Good" 

titleize這是錯誤的,因爲 '和' 和 'A' 應該是小寫。明顯。

所以,我能做的

"One and a Half Is always Good".titleize.tr('And', 'and') #=> "One and a Half Is always Good" 

我的問題:我該如何使「A」的「一」,也沒有留下「始終」到「永遠」?

+0

\ BA \ b 的\ b詞邊界一致。你正在尋找正則表達式,對吧? – 2010-12-18 07:10:35

+0

是的!那麼它將如何工作? – 2010-12-18 07:36:20

+0

''一個半是總是好的'.gsub(/ \ bA \ b /,'a')#=>「一個半永遠是好的」 – 2010-12-18 08:11:38

回答

2

該做的:

require 'active_support/all' 
str = "one and a half is always good" #=> "one and a half is always good" 

str.titleize.gsub(%r{\b(A|And|Is)\b}i){ |w| w.downcase } #=> "One and a Half is Always Good" 

str.titleize.gsub(%r{\b(A(nd)?|Is)\b}i){ |w| w.downcase } #=> "One and a Half is Always Good" 

把你任的最後兩行的選擇。正則表達式模式可以在其他地方創建並作爲變量傳入,用於維護或代碼清潔。

+0

這是完美的。非常感謝你! – 2010-12-18 15:54:48

2

我喜歡格雷格的雙線(先標題化,然後用正則表達式來表達選定的單詞。)FWIW,這是我在項目中使用的函數。經過良好測試,雖然更詳細。你會注意到,我重寫titleize中的ActiveSupport:

class String 
    # 
    # A better titleize that creates a usable 
    # title according to English grammar rules. 
    # 
    def titleize 
    count = 0 
    result = [] 

    for w in self.downcase.split 
     count += 1 
     if count == 1 
     # Always capitalize the first word. 
     result << w.capitalize 
     else 
     unless ['a','an','and','by','for','in','is','of','not','on','or','over','the','to','under'].include? w 
      result << w.capitalize 
     else 
      result << w 
     end 
     end 
    end 

    return result.join(' ') 
    end 
end 
+0

字符串有一個標題?你的意思是你重寫了Active_Support的標題。 – 2010-12-18 11:00:57

+0

呃,是的 - 你一定是對的。我會改變這一點。 – Dogweather 2010-12-18 12:44:16

+0

FWIW,將字符串數組轉換爲哈希查找可能是個好主意。調用'Array #include?'每個字符串中的每個單詞要被標題化看起來效率不高。 'stopwords = Hash [%w [a an and by for ...] .map {| w | [w,true]} .flatten] ...除非停用詞[w] ...' – Phrogz 2010-12-18 15:14:56