From: Jeff Wood Date: 2005-08-25T00:45:31+09:00 Subject: Re: Novice Q: What's the difference between /\s*/ and /(\s)*/? 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 ) ... Remember that if you define a group to be inside an optional region of the regular expression, that group will return nil. So, if you were parsing phone numbers in the format of: ###-###-#### You could save yourself a bit of code and define your regex to be: a = "My phone number is : 800-555-1212" b = /(\d{3})\-(\d{3})\-(\d{4})/ c = b.match( a ) if c puts c[0] # returns the complete match : 800-555-1212 puts c[1] # returns group 1 : 800 puts c[2] # returns group 2 : 555 puts c[3] # returns group 3 : 1212 else puts "Not a match" end I hope that helps. Remember that [0] always exists, but the other items only exist if you define groups within your regular expression. j. On 8/24/05, Gavin Kistner wrote: > On Aug 24, 2005, at 7:47 AM, Gavin Kistner wrote: > > " \t\nHello".match( /^\s*(\w+)/ ) #=> "Hello" , nil > > " \t\nHello".match( /^(\s)*(\w+)/ ) #=> "\n" , "Hello" > > " \t\nHello".match( /^(\s*)(\w+)/ ) #=> " \t\n" , "Hello" > > "\t Hello".match( /^\s*(\w+)/ ) #=> "Hello" , nil > > "\t Hello".match( /^(\s)*(\w+)/ ) #=> " " , "Hello" > > "\t Hello".match( /^(\s*)(\w+)/ ) #=> "\t " , "Hello" > > "\n \tHello".match( /^\s*(\w+)/ ) #=> "Hello" , nil > > "\n \tHello".match( /^(\s)*(\w+)/ ) #=> "\t" , "Hello" > > "\n \tHello".match( /^(\s*)(\w+)/ ) #=> "\n \t" , "Hello" > > > > Three more pertinent data points: > > "Hello".match( /^\s*(\w+)/ ) #=> "Hello" , nil > "Hello".match( /^(\s)*(\w+)/ ) #=> nil , "Hello" > "Hello".match( /^(\s*)(\w+)/ ) #=> "" , "Hello" > > > -- "So long, and thanks for all the fish" Jeff Wood