Posted about 1 month ago. Visible to the public. Repeats.

Ruby: Using named groups in Regex

An alternative of using a multiple assignment for a Regex are named groups. Especially when your Regex becomes more complicates it is easier to understand and to process.

Note:

  • In case a string does not match the pattern, .match will return nil.
  • With Ruby 2.4 the result of .match can be transformed to a Hash with named_captures. This allows you to use methods like slice or fetch on the result.

Example with a multiple assignment

Copy
PRODUCT_PATTERN = /\A(.+) S\/N:(\w+)\z/ product = "Bosch S/N:WS200LN12" manufacturer, serial_number = product.match(PRODUCT_PATTERN)&.captures # or manufacturer = product[PRODUCT_PATTERN, 1] serial_number = product[PRODUCT_PATTERN, 2]

Example with named groups (<2.4)

Copy
PRODUCT_PATTERN = /\A(?<manufacturer>.+) S\/N:(?<serial_number>\w+)\z/ product = "Bosch S/N:WS200LN12" match = product.match(PRODUCT_PATTERN) || {} manufacturer = match[:manufacturer] serial_number = match[:serial_number] # or manufacturer = product[PRODUCT_PATTERN, :manufacturer] serial_number = product[PRODUCT_PATTERN, :serial_number]

Example with named groups (>=2.4)

Copy
PRODUCT_PATTERN = /\A(?<manufacturer>.+) S\/N:(?<serial_number>\w+)\z/ product = "Bosch S/N:WS200LN12" match = product.match(PRODUCT_PATTERN) manufacturer = match&.named_captures&.fetch('manufacturer') serial_number = match&.named_captures&.fetch('serial_number')

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Emanuel De
Last edit:
2 days ago
by Emanuel De
Keywords:
captured, groups
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more