Ruby正则表达式搜索

时间:2011-02-22 20:32:45

标签: ruby regex

我正在编写一个脚本来搜索%{}符号的HTML文本块,用动态变量替换它们。

出于某种原因,我的正则表达式无效。

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

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

我确信它的一些简单......关于什么可能出错的任何想法?

4 个答案:

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

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

答案 2 :(得分:1)

由于您的文字不在字符串的开头或紧跟在新的字符后面,因此您不应使用行首锚(^):

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

查看在线工作:ideone

答案 3 :(得分:0)

它是由初始插入符^引起的,它代表“行首”。如果你删除它,它应该匹配。

相关问题