# Matchdata

**URL:** <https://www.ruby-forum.com/t/matchdata/77012>\
**Category:** Ruby\
**Created:** [November 23, 2006, 12:13pm UTC](https://www.ruby-forum.com/t/matchdata/77012 "2006-11-23T12:13:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nuby2ruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/54ee81/32.png) [@nuby2ruby](https://www.ruby-forum.com/u/nuby2ruby)\
**Post date:** [November 23, 2006, 12:13pm UTC](https://www.ruby-forum.com/t/matchdata/77012/1 "2006-11-23T12:13:34Z")

</div>

I have a file that I want to scan for matches of a regular expression.  
The expression crosses multiple lines (/m), so I can’t use each\_line.  
I’ve been using scan, but I now need a match data object for each match  
so I can get the position of the match. Is there a way to loop through  
matches and get the match data for each match when all the data is in a  
single string with multiple matches in it?

For arguments sake, here is the data:

public sub method1()  
op1()  
op2()  
end sub

public sub method2(lots, of,  
variables, over, many, lines)  
op1()  
op2()  
end sub

public function method3() as string  
op1()  
op2()  
end function

Here is the regular expression:  
/^(?:(private|public)\s)?(sub|function)\s(.+?)\s?(._?)(?:\sas\s(.+?))?(?:’._?)?$.\*?end\s\2/im

What is current returned by scan:  
[‘public’,‘sub’,‘method1’,nil]  
[‘public’,‘sub’,‘method2’,nil]  
[‘public’,‘function’,‘method3’,‘string’]

What I want:  
[MatchData,MatchData,MatchData]

Jeremy

---

<div class="post-metadata">

**Author:** ![nuby2ruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/54ee81/32.png) [@nuby2ruby](https://www.ruby-forum.com/u/nuby2ruby)\
**Post date:** [November 23, 2006, 12:19pm UTC](https://www.ruby-forum.com/t/matchdata/77012/2 "2006-11-23T12:19:35Z")

</div>

On 11/23/06, Jeremy W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:  
[snip]

> What I want:  
> [MatchData,MatchData,MatchData]

something like this

‘aa’.scan(/a/) {|i| p $~ }

---

<div class="post-metadata">

**Author:** ![nuby2ruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/54ee81/32.png) [@nuby2ruby](https://www.ruby-forum.com/u/nuby2ruby)\
**Post date:** [November 23, 2006, 5:35pm UTC](https://www.ruby-forum.com/t/matchdata/77012/3 "2006-11-23T17:35:23Z")

</div>

thanks, that worked great

Simon S. wrote:

> –
> 
> Simon S.

–

_Jeremy W._  
Serval Systems Ltd.

[www.servalsystems.co.uk](http://www.servalsystems.co.uk) [http://www.servalsystems.co.uk](http://www.servalsystems.co.uk)  
Tel: 01342 331940  
Fax: 01342 331950
