2011-02-22 32 views
1

我正在研究一個腳本,用於搜索%{}標誌的HTML文本塊,以便用動態變量替換它們。Ruby正則表達式搜索

由於某種原因,我的正則表達式不工作。

str = "<p>%{urgent_personal_confidential}</p>" 

regex = /^%\{(.*)\}/ 
puts str.match(regex) 

我相信它的一些簡單的...有什麼想法可能是錯誤的?

回答

7

Ruby已具有該功能built-in into String

"The quick brown %{animal1} jumps over the lazy %{animal2}" % { :animal1 => "fox", :animal2 => "dog" } 

結果是

"The quick brown fox jumps over the lazy dog" 
+0

我不知道你可以做到這一點!我愛Ruby的男人更多! – dennismonsewicz 2011-02-22 20:40:28

1

由於您的文字是不是在字符串的開頭或不應該使用開始的行一個錨(^)新行字符後,立即:

regex = /%\{(.*)\}/ 

看到它聯機工作:ideone

+0

謝謝!這解決了我的問題!我會確保將它標記爲答案,一旦我可以:) – dennismonsewicz 2011-02-22 20:35:07

0

這是由初始插入符號^引起的,它代表「行首」。如果你刪除它,它應該匹配。

2

也許我誤解了,但是你不能只用Ruby的內置字符串插值嗎?

ruby-1.9.2-p136 :001 > str = "<p>%{urgent_personal_confidential}</p>" 
=> "<p>%{urgent_personal_confidential}</p>" 
ruby-1.9.2-p136 :002 > str % { :urgent_personal_confidential => "test" } 
=> "<p>test</p>"