Skip to main content
2 of 3
Removed dictionary reverse-lookup request, and small detail which didn't seem to contribute to the question.
Robert Harvey
  • 200.7k
  • 55
  • 470
  • 683

Are there known constructs for two-way string pattern matching?

I've often come across situations where pattern matching in a string is formalized, but the reverse is not.

Say I invent a new string pattern that can be expressed by regex /([0-9a-z])*:([0-9a-z])*@([0-9a-z])/.

Expressing that regex as data to your friendly local programming language, the standard lib will be able to convert foo:bar@4040404 into ["foo", "bar", "4040404"].

How about converting it the other way? Based on what I've done so far, I will need to duplicate the pattern—into, for example: "#{m[0]}:#{m[1]}@#{m[2]}".

In other words, can we produce text out of structured data and regex patterns, using the same data for parsing as to the other way?

The other way for which we also have a lot of tools already.—One might call that templating or compiling.—What if the format is the same going both ways? Can we reuse the same code?