Keith Schacht’s Weblog

Subscribe

💡 TIL: Regex within string square brackets

24th February 2025

I’ve always known that Ruby supports ranges within a string’s square brackets. So in addition to the simple `name[4]` I can do `name[2..4]` and `name[2...]` and `name[-1]`. But I just learned you can put regex in the square brackets for more dynamic substring selectors: `“me+abc123@email.com”[/.+\+(.+)@(.+)/, 2]` will give you the subdomain of the email address. It even works with named capture groups! `“123.45”[/(?<dollars>\d+)\.(?<centers>\d+)/, :dollars]` will give you the dollars. The article has a few other notable examples.

via

More recent articles

This is Regex within string square brackets by Keith Schacht, posted on 24th February 2025.

Part of series Today I Learned

  1. Rails ActiveRecord has a .sole method - Nov. 26, 2024, 11:15 p.m.
  2. pick is the single-value version of pluck in Rails - Nov. 26, 2024, 11:24 p.m.
  3. Elegant solution to versioning an API - Feb. 24, 2025, 3:13 p.m.
  4. Regex within string square brackets - Feb. 24, 2025, 3:16 p.m.
  5. Ruby's clamp method reduces conditionals - Feb. 24, 2025, 3:19 p.m.

Next: Ruby's clamp method reduces conditionals

Previous: Elegant solution to versioning an API