1

I've been trying to find something like this in the docs, but failed. What I want is to iterate over regular expression matches in a string, and passing MatchData to the block.

  • There's Regexp#match, but it only finds one match;
  • There's String#scan, but the block receives only the captures array or the match string, not full MatchData. This especially sucks with Oniguruma, as you lose the named capture capability.
  • There's also Regexp::last_match, so I could actually go the scan route, but it seems ugly and inelegant.

Am I missing something?

Amadan
  • 191,408
  • 23
  • 240
  • 301

2 Answers2

2

See Is there a function like String#scan, but returning array of MatchDatas?

It looks like your best bet is to use String#scan and Regexp.last_match.

Community
  • 1
  • 1
Scott Olson
  • 3,513
  • 24
  • 26
  • Yeah, I was afraid that would be the answer. Inelegant, especially given that no monkey business is needed in case of a single match. – Amadan Jul 20 '12 at 01:28
0

Yes, you are missing something. From the MatchData documentation:

MatchData is the type of the special variable $~, and is the type of the object returned by Regexp#match and Regexp.last_match. It encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $', $`, $1, $2, and so on.

The important bit is in bold.

You already have ALL the matches in a single MatchData object. Isn't that what you want?

Strelok
  • 50,229
  • 9
  • 102
  • 115
  • 1
    No - you have all captures of a single match in a `MatchData`. If you have multiple matches, you need multiple `MatchData` objects. – Amadan Jul 20 '12 at 01:27
  • I think this question has the correct answer then: http://stackoverflow.com/questions/6804557/how-do-i-get-the-match-data-for-all-occurrences-of-a-ruby-regular-expression-in – Strelok Jul 20 '12 at 01:29
  • It's a working answer, but I wouldn't say it's a correct one (from Ruby, not from i-blis). I love Ruby, but this here is a wart. – Amadan Jul 20 '12 at 01:33