From: Jeff Wood Date: 2005-08-25T01:09:20+09:00 Subject: Re: Novice Q: What's the difference between /\s*/ and /(\s)*/? Regarding nil values for groups if you define your regular expressions like this : a = "My phone number is : 555-1212" b = /((\d{3})\-)?(\d{3})\-(\d{4})/ c = b.match( a ) puts c.to_a c should be [ "555-1212", nil, nil, "555", "1212" ] [0] holds a copy of the complete match [1] matches the parens from char 0 through char 10 - The following question mark states that either 0 or 1 instance of the previous group should be accepted in the pattern match. [2] matches the parens from char 1 through char 7 [3] matches the parens from char 12 through char 18 [4] matches the parens from char 21 through char 27 I hope that made sense too. j. On 8/24/05, David A. Black wrote: > Hi -- > > On Thu, 25 Aug 2005, Jeff Wood wrote: > > > Ok, now for a clean and simple answer... > > > > The parenthesis create "groups". Groups give you the ability to save > > away parts of the matched pattern for easy access after a match has > > been made. And yes, the O'Reilly book "Mastering Regular Expressions" > > would be a good read it explains this concept quite completely. > > > > When you use Regexp#match, if you find a match, you are returned a > > MatchData object which provides an [] API for standard array style > > access. > > > > Element 0 ( [0] ) provides the COMPLETE match. If you defined any > > groups in the regular expression, they will then appear as additional > > elements in the MatchData [] array. Each group is then accessable > > using ordinals ( [1] .. [9] I don't know what happens after 9, I've > > never needed that many ) ... > > I believe that would be 10 :-) > > irb(main):003:0> m = /(((((((((((a)))))))))))/.match("a") > => # > irb(main):004:0> $10 > => "a" > irb(main):005:0> m[10] > => "a" > > > > Remember that if you define a group to be > > inside an optional region of the regular expression, that group will > > return nil. > > I'm not sure what you mean there. > > irb(main):009:0> /((a)?)?/.match("a").to_a > => ["a", "a", "a"] > > > David > > -- > David A. Black > dblack@wobblini.net > > -- "So long, and thanks for all the fish" Jeff Wood