我正在编写一个脚本来搜索%{}
符号的HTML文本块,用动态变量替换它们。
出于某种原因,我的正则表达式无效。
str = "<p>%{urgent_personal_confidential}</p>"
regex = /^%\{(.*)\}/
puts str.match(regex)
我确信它的一些简单......关于什么可能出错的任何想法?
答案 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)
答案 3 :(得分:0)
它是由初始插入符^
引起的,它代表“行首”。如果你删除它,它应该匹配。