From: Matthew Kerwin Date: 2012-09-01T14:09:40+09:00 Subject: Re: Regular Expression Conundrums On 1 September 2012 14:02, Stan Stanislaus wrote: > http://pastie.org/4643789 > > Why, in Case 2, do I have to escape the asterisk twice to keep the > program from thinking /\ is a substarter? Thank you all for your help! I > really appreciate this. Remember that the parameter you're passing in is a string. In string literals, backslashes that precede any non-special characters (such as asterisk) are essentially ignored, so "/\*/" is the same as "/*/" (i.e. three characters: slash, star, slash). Regexp.new "/\*/" # => /\/*\// Regexp.new "/*/" # => /\/*\// That resulting Regexp pattern is an escaped forward-slash, a star, and an escaped forward slash; so it will match zero or more forward-slashes followed by another forward-slash. That's the same as %r{/*/} or %r{/+} Thus the numbers you get back are actually just the positions of every sequence of slashes in the string. It doesn't think "/\" is a substarter, just "/" Putting a second backslash in the string literal means you have four characters in your string: slash, (escaped) backslash, star, slash; which interpreted as a Regexp means: a slash followed by an (escaped) asterisk, followed by a slash. You could use Regexp#quote to take away the special meaning of the star in your string; e.g. [line 20] regex = Regexp.new( Regexp.quote regex_string ) and/or you could allow the regex_string parameter to be regexp object. That way you could call, for example: substarters = this_room_data.all_occurances "/*/" # no need to escape regex characters substarters = this_room_data.all_occurances %r{/\*/} # no need to escape string characters No double-escaping; twice as much win. -- Matthew Kerwin, B.Sc (CompSci) (Hons) http://matthew.kerwin.net.au/ ABN: 59-013-727-651 "You'll never find a programming language that frees you from the burden of clarifying your ideas." - xkcd