DEV Community

Discussion on: How do you regex?

Collapse
 
jeremyf profile image
Jeremy Friesen

For tools, I like to use Ruby to write my regex. I often refer to the documentation. I invariably pair the regex with lots of local tests.

Below is a basic test. I save the code to a file (e.g. regexp.rb) and then run ruby regexp.rb.

THE_REGEX = %r{\d+}
def the_matcher(text)
  THE_REGEX.match?(text)
end

if __FILE__ == $0
  [
    ["123", true],
    ["abc", false],
  ].each do |text, expected|
    actual = the_matcher(text)
    if actual == expected
      puts "SUCCESS: for #the_matcher(#{text.inspect})"
    else
      puts "FAILURE: Expected #the_matcher(#{text.inspect}) to return #{expected}, got #{actual}"
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

I favor these basic tests as I'm writing regular expressions as they are super fast to run. And are easy to later port into the test suite of the application (which depending on how the application tests are constructed might be faster or slower to run).

For types of problems, I've used it for: