Menu

1 / 3

Making legacy regexes readable — without changing what they match

DEV Community: javascript·FF·about 17 hours ago
#uvscw3Y1
#devtojavascript#devto#dev#line#comments
Reading 0:00
15s threshold

A pattern like this ships in real projects every day:

^(?\[(?:[A-Za-z0-9_.-]+)\])|^(?[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^#\n]*)\s*(?:#.*)?$

Enter fullscreen mode

Exit fullscreen mode

An INI-line parser: a section header or a key–value pair, three quoting modes for the value, trailing comments. Perfectly readable — to the person who wrote it, today. Come back in three months, or hand it to a teammate, and the review comment is always the same: what does this actually match?

Formatting solves this the way it's solved for every other language. The same pattern, laid out by structure:

^ (? \[(?:[A-Za-z0-9_.-]+)\]) | ^ (? [A-Za-z_][A-Za-z0-9_]*) \s* = \s* (? " (?: [^"\\] | \\ . )* " | ' (?: [^'\\] | \\ . )* ' | [^#\n]* ) \s* (?:\#.*)? $

Enter fullscreen mode

Exit fullscreen mode

Two branches instead of one buried | ; three quote styles you can point at; a comment-stripping tail that's obviously a tail.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.