From: tietyt@...
Date: 2005-06-23T11:30:37+09:00
Subject: Getting a list of results from one regular expression
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: