Home
Regex tester

Source text    History: Prev source text  Next source text

The regex to apply to the text    History: Prev regex  Next regex
//

ignore case   global   multiline  

Results

text that didn't match  matched expression  (sub-expression)

(Dec '07-Jan '08) This applet was created as an exercise to re-learn JavaScript after a long absence, and to help me learn regular expressions, which I hadn't been exposed to much in my Windows development career.

This runs completely in the browser, and lets you test out regex expressions against your own text. It makes use of JavaScript's RegExp.exec method to find all the matches, including subexpressions.

The UI for the page is rather straightforward. When you click [Analyze], it runs the regex against the text and displays the result. Each time you analyze the text, it also checks the text and the regex against their respective history lists. If either one (or the I/G/M options) have changed, it adds that version to the history list. It displays Back & Forward buttons to let you go back to earlier versions to play with again.

The only really difficult part of the project was in building the highlighted result string. When you call RegEx.exec, it tells you what substrings matched the regex & which ones matched the subexpressions, but it doesn't tell you where in the source text these matches are. If it did, you'd know where to place the necessary html codes to form the highlights. But at least it places the matches in order in the array. So we do an exact search for each matched string in turn from our current position in the source text, then append onto the result string the "prefix" highlighting html, the matched text, then the "suffix" highlighting html, then any plain text in the source that comes before the next match.

I think it's ugly, but I don't see any more elegant way of building up the result string given the limitations of the info that Regex.exec returns. It might be a bit simpler to call String.replace with the regex, passing it a callback function to process each match in turn. Then the callback would return (sPrefix + sMatched + sSuffix). However, to highlight the subexpressions we'd still have to search the matching text to locate them ourselves. Besides, you can't programmatically tell String.replace which attributes (i/g/m) to use—and we want the user to be able to specify these on the fly. So I think this code is as simple as it's ever going to get.