DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Emad has posted 58 posts at DZone. View Full User Profile

create a regular expression testing playground using ruby and sinatra

03.02.2014
| 1628 views |
  • submit to reddit
require 'sinatra' # gem install sinatra --no-ri --no-rdoc
set :port, 3000
html = <<-EOT
<html><head><style>
#regex,#text{ width:100%; font-size:15px; display:block; margin-bottom:5px; }
#text{ height: 200px; }
span{ background:rgb(230,191,161); display:inline-block; border-radius:3px;}
</style></head><body>

	<input id="regex" placeholder="Regex"/>
	<textarea id="text" placeholder="Text"></textarea>
	<div id="result"></div>

	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
	<script>
	$('#regex,#text').keyup(function(){
			$.get('/preview',{
				reg:$('#regex').val(),
				text:$('#text').val()
			},function(r){
				$('#result').html(r);
			});
	});
	</script>

</body></html>
EOT

get('/'){ html }
get '/preview' do 
	begin
		params['text'].gsub(/(#{params['reg']})/,'<span>\1</span>')
	rescue
		'Your regex is invalid'
	end
end