Read more

Ruby: You can nest regular expressions

Henning Koch
September 29, 2021Software engineer at makandra GmbH

Ruby lets you re-use existing RegExp objects by interpolating it into new patterns:

locales_pattern = /de|en|fr|es/i

html_tag_pattern = /<html lang="#{locales_pattern}">/
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Any modifiers like /i or /x will be preserved within the interpolated region, which is pretty cool. So in the example above only the interpolated locales are case-insensitive, while the pattern around it (/<html .../) remains case-sensitive.

Posted by Henning Koch to makandra dev (2021-09-29 11:28)