View Problem

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
ExpandDiskEdit
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
ExpandDiskEdit
ruby
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}
ExpandDiskEdit
cpp C++/CLI .NET 2.0
Match^ match = Regex::Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)");

while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}
ExpandDiskEdit
fsharp
let list = new ResizeArray<string>()
let mutable regmatch = (Regex.Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)"))

while regmatch.Success do
list.Add(regmatch.Groups.[1].Captures.[0].ToString() ^ regmatch.Groups.[2].Captures.[0].ToString())
regmatch <- regmatch.NextMatch()
done

for word in list do printfn "%s" word done
ExpandDiskEdit
fsharp
// A solution without mutation:
let results =
Regex.Matches("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)")
|> Seq.cast
|> Seq.map (fun (regmatch: Match) ->
regmatch.Groups.[1].Captures.[0].ToString() + regmatch.Groups.[2].Captures.[0].ToString()
)
|> List.ofSeq
ExpandDiskEdit
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ it[1] + it[2] }
ExpandDiskEdit
groovy
list = []
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
ExpandDiskEdit
groovy
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
ExpandDiskEdit
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ all, name, num -> "$name$num" }
ExpandDiskEdit
groovy 1.6.1+
list = text.findAll(regex){ _, name, num -> "$name$num" }
ExpandDiskEdit
groovy 1.6.1+
list = text.findAll(regex){ it[1] + it[2] }

Submit a new solution for ruby, cpp, fsharp, or groovy
There are 11 other solutions in additional languages (clojure, csharp, erlang, fantom ...)