1

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>%{urgent_personal_confidential}</p>"

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

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

4 Answers 4

7

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

1 Comment

Thanks! This fixed my issue!!! I will make sure to mark it as the answer once I can :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.