by brigandish · 6y ago · 0 comments
Inscrutability - use the `x` modifier and allow whitespace and comments, e.g.
/^(\\^+|_+|=)?([a-gA-G])(,+|'+)?(\\d*)(\\/)?(\\d*)$
becomes: /^
( \\^+ | _+ | = )? # sharps and flats
( [a-gA-G] ) # notes
( ,+ | '+ )?
( \\d* ) # duration
( \\/ )? # fractions
( \\d* ) # more duration? I'd need to read the spec
$/x
and use different delimiters to remove escaping of slashes: <^
( \\^+ | _+ | = )? # sharps and flats
( [a-gA-G] ) # notes
( ,+ | '+ )?
( \\d* ) # duration
( / )? # fractions
( \\d* ) # more duration? I'd need to read the spec
$>x
That's already much more readable, but then we have complaint number 2, composability. If you language supports it then use interpolation: SHARPS_AND_FLATS = /\\^+ | _+ | =/x
NOTES = /[a-g]/i
<^
(#{SHARPS_AND_FLATS})? # sharps and flats
(#{NOTES}) # notes
( ,+ | '+ )?
( \\d* ) # duration
( / )? # fractions
( \\d* ) # more duration? I'd need to read the spec
$>x
You see how it could go on. I'm not saying regex are always the right solution and not all languages have access to the same tools but there's often a lot that can be done to mitigate the awfulness (and a lot more here, lookarounds, named captures etc).The `x` modifier is the #1 fix, I never write anything above the most simple regex without it, and for the life of me I can't understand why it's hardly ever used.
SHARPS_AND_FLATS = /\\^+ | _+ | =/x
NOTES = /[a-g]/i
p = <^
(?<pitch>#{SHARPS_AND_FLATS})? # sharps and flats
(?<notes>#{NOTES}) # notes
( ,+ | '+ )?
( \\d* ) # duration
( / )? # fractions
( \\d* ) # more duration? I'd need to read the spec
$>x
match_data = p.match(music)
match_data[:pitch] # => "#"
match_data[:notes] # => "ADEADE"
Much more readable.It's incredible how useful it is and yet by not being the default every regex implementation has nudged their users to write inscrutable regular expressions for decades.
Still, there's not much to the `x` modifier, you just need to know that it will ignore implicit whitespace and comments (# blah blah) so you must use `\s` or `\t` etc when you really want to match some whitespace. Otherwise you can do things like:
"Hello, world!".split(/ [ \s , ]+ # this splits on at least one space or comma /x)
Which is overkill for a simple pattern (then again, why not?) but unbelievably useful for a complex one. Add spaces and newlines until it's readable.It's a small change but a big effect.