From: Michael Selig Date: 2008-09-19T12:58:26+09:00 Subject: [ruby-core:18721] Re: Encoding Safe Regexp.escape() On Fri, 19 Sep 2008 06:48:41 +1000, James Gray wrote: > As part of my ongoing process to make CSV m17n savvy, I'm needing an > encoding safe Regexp.escape(). I'm currently using basically this code: > > @re_esc = "\\".encode(@encoding) > @re_chars = %w[ \\ . [ ] ^ $ ? > * + { } ( ) | ].map { |s| s.encode(@encoding) } > > # ... > > def escape_re(str) > str.chars.map { |c| @re_chars.include?(c) ? @re_esc + c : c }.join > end > > First question: are there logic flaws there or is escaping a string to > safely use in a Regexp that simple? Just for fun, I ran: ruby -e 'p ("\x00".."\x7f").select {|c| c != Regexp.escape(c)}' and got: ["\t", "\n", "\v", "\f", "\r", " ", "#", "$", "(", ")", "*", "+", "-", ".", "?", "[", "\\", "]", "^", "{", "|", "}"] so it looks like Regexp#escape is escaping more that your code does. Cheers Mike