开发者

Ruby regex search

I'm working on a script to search through a block of HTML text for %{} signs to replace them with dynamic variables.

For some reason my regex is not working.

str = "<p>%{urge开发者_如何学JAVAnt_personal_confidential}</p>"

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

I am sure its something simple... any ideas on what could be wrong?


Ruby already has that feature built-in into String.

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

The result is

"The quick brown fox jumps over the lazy dog"


Maybe I'm misinterpreting, but can't you just Ruby's built-in string interpolation?

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>" 


Since your text isn't at the start of the string or immediately after a new line character you shouldn't use a start-of-line anchor (^):

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

See it working online: ideone


It is caused by the initial caret ^, which stands for "beginning of line". If you remove it, it should match.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜