From: Robert Klemme Date: 2005-12-20T06:47:50+09:00 Subject: Re: regular expressions question ako... wrote: > yes, thank you. this is a better description of the problem. i am not > a native english speaker, so may be this is one of the reasons why my > question is not clear. > > i saw a solution to this problem that uses split at the end. it of > course won't work if you change your example and allow quoted strings > in source-words and destination-words. a quoted string can contain > anything, spaces too and your keywords too, so the subsequent split > won't work. > > well, i did not realise that the term "group's captures" is that rare. > i thought it was a standard term. but may be i am brainwashed by > microsoft. so i have this code in .net which might help to clarify > what i am talking about: > > string text = "One car red car blue car"; > string pat = @"^(?:(\w+)\s+)*(\w+)$"; > Regex r = new Regex(pat, RegexOptions.IgnoreCase); > > // Match the regular expression pattern against a text > string. > Match m = r.Match(text); > if (m.Success) > { > Console.WriteLine("match: [{0}]", m); > foreach (Group g in m.Groups) > { > Console.WriteLine("group: [{0}]", g); > foreach (Capture c in g.Captures) > { > Console.WriteLine("\tcapture: [{0}]", c); > } > } > } > > the output is: > > match: [One car red car blue car] > group: [One car red car blue car] > capture: [One car red car blue car] > group: [blue] > capture: [One] > capture: [car] > capture: [red] > capture: [car] > capture: [blue] > group: [car] > capture: [car] > > as you see, the first group is $0, the second group is $1, and the > third is $2. but $1 and $2 contain captures too. it is like if $1 and > $2 were arrays in Ruby. > > in my opinion this is a big limitation of ruby's regular expressions. > it just must be as powerful as .net ; -) > > konstantin I don't know whether your question was answered in the lengthy thread already. In case not: in Ruby to get all matches of a group you need to iterate through the whole string with #scan. There is no such thing as this feature of .net - and frankly I haven't missed it so far. To get at all the words in your example this is sufficient: >> s = "One car red car blue car" => "One car red car blue car" >> s.scan /\w+/ => ["One", "car", "red", "car", "blue", "car"] If you actually need group matches, you'll have to do something like this >> s.scan(/\w(\w+)/).map{|m| m[0]} => ["ne", "ar", "ed", "ar", "lue", "ar"] alternative >> ma=[] => [] >> s.scan(/\w(\w+)/) {|m| ma << m[0]} => "One car red car blue car" >> ma => ["ne", "ar", "ed", "ar", "lue", "ar"] Of course this is quite a silly example... The main point here is that you must refrain from anchoring the regexp at the beginning if you want to iterate like this. HTH robert