From: Mark Hubbart Date: 2005-06-23T11:47:19+09:00 Subject: Re: Getting a list of results from one regular expression On 6/22/05, tietyt@gmail.com wrote: > Hello I'm new to Ruby. I've read most of the pragmatic programmer > guide but couldn't find anything that explained how to do this. > > To summarize my whole question: how do I get EVERY match of a regular > expression (instead of just the first)? > > Here's my situation, I've got this long string that contains XML. I > would like to parse it. Specifically, I want to search this string for > all instances of a pattern like /stringAlias="(.*)"/ > > I'm no pro with regex, but I think that will find a match for a string > that looks like this: stringAlias="BLAH" > > And because of the (.*), the result will be BLAH > > Now this is all fine and good. But what I can't figure out is how to > get every match in an array (instead of just the first match. > > If i have stringAlias="BLAH" ... stringAlias="BLEH" how do I get an > array that is ["BLAH", "BLEH"]? > > Keep in mind that there are a dynamic number of matches for > stringAlias="(.*)" > > > This is the code I wrote to try to do it: > > def ... > @aliases = [] > matchedData = /stringAlias="(.*?)"/.match(@data) > @aliases = matchedData.to_a > puts @aliases > end > > The length of the array is 2 and the result is this: > stringAlias="OP" > OP > > Even though the data is this: > sortOrder="0" stringAlias="OP"> > > > sortOrder="1" stringAlias="1"> > > > sortOrder="2" stringAlias="2"> > > > sortOrder="3" stringAlias="3"> > > > sortOrder="4" stringAlias="4"> > > Regexp#match only gives the first match; the matchdata object is sort of an array of the entire match, followed by the subexpression matches. What you want is String#scan: (warning, untested) regexp = /stringAlias="(.*?)"/ matches = @data.scan(regexp) Since the regexp has a subexpression matcher, that is what will be put into the array "matches". You'll get an array something like this: [["OP"],["1"],["2"], ... ] (each match has it's own subarray, since it's a subexpression match) Check out the docs for String#scan for more info... cheers, Mark