How To: Regular Expression Tester
It always takes me a few tries to get my regular expressions right. I thought it would be handy if I could take a regular expression and test text to match it against, edit both in real-time and see the results. I thought such a project would be pretty quick and easy in Ruby on Rails (which I'm currently teaching myself).
First I created a new project:
I don't need to store any data, so I added a single controller:
regtest_controller.rb:
First I created a new project:
rails regtester
I don't need to store any data, so I added a single controller:
ruby script/generate controller Regtest index
Code
index.rhtml:<html>
<head>
<title>Regular Expression Tester</title>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<%= start_form_tag({:action => "#"}, :id => "regexp-form") %>
<table>
<tr>
<td>RegExp: <%= text_field_tag :pattern %></td>
<td> </td>
</tr>
<tr>
<td valign="top"><%= text_area_tag :match_text, nil, :size => "40x20" %></td>
<td id="results-area" valign="top"></td>
</tr>
</table>
<%= end_form_tag %>
<%= observe_form "regexp-form", :frequency => 1, :update => "results-area", :url => {:action => "find_matches" } %>
</body>
</html>regtest_controller.rb:
class RegtestController < ApplicationController
def index
end
def find_matches
begin
pattern = Regexp.new(params[:pattern])
@results = params[:match_text].gsub(pattern, '<b>\&</b>')
rescue RegexpError
@results = "Invalid Regular Expression"
end
render :text => @results
end
endImprovements
One limitation right now it that the match highlighting is pretty mediocre. The highlighting may not be apparent and it doesn't highlight whitespace. Instead of bold tags you could try something like:<span style="gt;«</span>\&<span style="color: red">»</span>