Another Word For It Patrick Durusau on Topic Maps and Semantic Diversity

August 22, 2016

Regexer [JavaScript Regexes – Railroad Diagrams]

Filed under: Javascript,Regexes — Patrick Durusau @ 4:43 pm

Regexer

From the documentation page:

The images generated by Regexper are commonly referred to as “Railroad Diagrams”. These diagram are a straight-forward way to illustrate what can sometimes become very complicated processing in a regular expression, with nested looping and optional elements. The easiest way to read these diagrams to to start at the left and follow the lines to the right. If you encounter a branch, then there is the option of following one of multiple paths (and those paths can loop back to earlier parts of the diagram). In order for a string to successfully match the regular expression in a diagram, you must be able to fulfill each part of the diagram as you move from left to right and proceed through the entire diagram to the end.

As an example, this expression will match “Lions and tigers and bears. Oh my!” or the more grammatically correct “Lions, tigers, and bears. Oh my!” (with or without an Oxford comma). The diagram first matches the string “Lions”; you cannot proceed without that in your input. Then there is a choice between a comma or the string ” and”. No matter what choice you make, the input string must then contain ” tigers” followed by an optional comma (your path can either go through the comma or around it). Finally the string must end with ” and bears. Oh my!”.

js-regex-example-460

JavaScript-style regular expression input and railroad diagram output.

Can you think of a better visualization for teaching regexes? (Or analysis when they get hairy.)

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress