From: Martin DeMello Date: 2003-01-08T07:53:08+09:00 Subject: Re: Regular expressions alternative Maur?cio wrote: > Hi, > > Wouldn't it be a good idea to create a option (say, b) for regular > expressions such that all characters (except / and \) would match > themselves unless preceeded by a backslash? For instance: Here's an alternative implementation. Usage: a = Regexp.nonmagic('string') # converts 'string' to a normal regexp The advantage is that you can now use a.source to embed your regexp into a larger regexp and have the larger regexp be normal (if you're a vi user you know how annoying having to escape metacharacters can be). --begin-- class Regexp class << self def nonmagic(s) special = Regexp.compile('^['+'.|()[]^{}+$*?'.split.map{|i| Regexp.quote(i)}.join+']$' ) r = s.scan(/(\\.|.)/).flatten.map {|i| case i when '\\\\'; Regexp.quote('\\') when /(\\(.))/ p, q = $1, $2 (p =~ special) ? p : q else; Regexp.quote(i) end }.join Regexp.compile(r) end end end --end--