zzamboni.org
  • Blog
  • Books
  • Code
  • Tags
  • Contact
  • About

Ruby

Below you will find pages that have the tag “ruby”

Capturing multiple matches in Ruby

March 31, 2010

To collect all regex matches in a string into an array, pass the regexp object to the string's scan() method, e.g.: myarray = mystring.scan(/regex/). Sometimes, it is easier to create a regex to match the delimiters rather than the text you are interested in. In that case, use the split() method instead, e.g.: myarray = mystring.split(/delimiter/). The split() method discards all regex matches, returning the text between the matches. The scan() method does the opposite.

If your regular expression contains capturing groups, scan() returns an array of arrays. Each element in the overall array will contain an array consisting of the overall regex match, plus the text matched by all capturing groups.

© 2024 Diego Zamboni
Made with love, coffee, and published using Hugo 0.136.5 + Ananke