technicalpickles

Open Source ProjectsCode that Might be Useful to You

Talks I've GivenOn Technologies and Ideas

ThoughtsWhere I Sometimes Write Things

Resume If You Believe In Those

Follow Me On

GitHubIf coding is your thing

TwitterIf you tweet

Escape Ruby Regular Expressions


If you’re doing any work with cucumber, it would do you well to become more familiar with Ruby regular expressions.

One useful piece of regular expression functionality is that you can interpolate variables inside an regular expression just like you would in a string. In cucumber, we could write a step like this:

Then /^I should see "(.*)"$/ do |text|
  assert_match /#{text}/, @response.body
end

There is a problem though. If text = 'Push Push (Lady Lightning) and @response_body = 'Push Push (Lady Lightning), the assertion would fail!

This is because there are some characters that have special meaning to regular expressions. Here, parentheses indicate capture groups which lets you extracted matched values. The net effect is the expression would match ‘Push Push Lady Lightning’ and capture “Lady Lighning”, but would not match ‘Push Push (Lady Lightning)’.

You can get around this by escaping characters with \ easily enough if we were doing it by hand. That won’t do for since we have a variable though. Fortunately, there is method Regexp.escape which takes a string and escapes any special characters.

We can update our step to look like:

Then /^I should see "(.*)"$/ do |text|
  assert_match /#{Regexp.escape(text)}/, @response.body
end

This assertion will now be successful if text = 'Push Push (Lady Lightning) and @response_body = 'Push Push (Lady Lightning) as you’d expected.

comments powered by Disqus