Plenty of Regular Expressions tools are available in the net. Most of them are free and quite quick. I have actually never thought that building such a tool can be done rather quickly, as far as the RegEx is part of JavaScript and is quite fast to work, once you know what you are doing.
Thus, this week I have decided to build a RegEx tool at vitoshacademy.com and I have managed – vitoshacademy.com/regex
Pretty much it is not much of philosophy – the JavaScript reads the input text and the RegEx and starts looking for a regex match. Once it is found, the input text is sliced (with my_text slice) and it continues looking further. All the results are written in the variable arr_result. At the end, each of the results in the variable arr_result is added to the results. Thus, we get something like this at the beginning:
And after we write w{6,}, requesting all words equal or above 6 letters, we get this:
The code is rather simple, but it is ok 🙂
This is the JScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$(document).ready(function () { $("#my_btn").click(function(){ var my_text = $('#my_text_input').text(); var my_regex = new RegExp('\\'+ $('#my_input').val()); //'\\d{5}' var my_result; var arr_result = []; while ((my_result = my_regex.exec(my_text)) != null){ arr_result.push(my_result[0]); my_text = my_text.slice(my_result.index + my_result[0].length); } for (counter = 0; counter < arr_result.length; counter++) { $("#my_div_result").append(arr_result[counter] + "<br>"); } }); $("#my_btn_clear").click(function() { $("#my_div_result").empty(); }); }); |
And the HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RegEx Tool</title> <link rel="stylesheet" type="text/css" href="my_style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="my_js.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body> <div id="main"> <h1 id="my_header">VitoshAcademy.Com RegEx Tool</h1> <div style="display: block;"> <textarea id = "my_text_input" type="text" rows="10" class="form-control">The idea is to show a my knowledge about programming and business analysis. I present any code, that I find interesting (usually C#, VBA, Python or JS) and I comment it. Reviews of IT books can be found as well. I hope you find something interesting here - www.vitoshacademy.com </textarea> </div> <p></p> <p>RegEx here <input id = "my_input" type="text" ></p> <input id="my_btn" type="button" class="btn btn-info" value="RegEx ME" /> <input id="my_btn_clear" type="button" class="btn btn-success" value="Clear" /> <hr> <div id="my_div_result"></div> </div> </body> </html> |
The whole code, with the few lines of CSS is available in my GitHub account here.
Enjoy it! 😀