From: "Ara.T.Howard" Date: 2004-05-14T07:03:58+09:00 Subject: Re: nasty regexp problem On 12 May 2004, Francis Hwang wrote: > Hi all, > > I discovered a strange bug in Lafcadio which I'm trying to work out, > but the regexp is getting really nasty. Basically, to commit text > values to the database I need to double any apostrophe, except those > that are preceded by a backslash. This has to account for apostrophes > at the beginning of the string, and multiline strings where the > apostrophe is at the start of a new line. Examples would be: > > "I can't drive 55" -> "I can''t drive 55" > "Don\'t escape here" -> "Don\'t escape here" > "'" -> "''" > "line 1\n' line 2" -> "line 1\n'' line 2" > > So here's the regexp that does it: > > value = value.gsub( /(^|[^\\\n])'/ ) { $& + "'" } > > which works fine, except I just discovered that it fails in one odd > case: > > "'''" -> "'''''" > > (That is, a single line of three apostrophes should become six > apostrophes, but instead it becomes five.) > > Any idea why this is doing it? I suspect I'm being too clever by > including the beginning of line in a grouping, and maybe that affects > how the regexp is processing the string? > > F. a "'" is escaped iff it is preceded with an odd number of "\" : ~ > cat a.rb strings = <<-'txt' I can't drive 55 Don\'t escape here line 1\n' line 2 1 ' 2 '' 3 ''' 4 '''' these are escaped \' \\\' \\\\\' these are not escaped \\' \\\\' \\\\\\' txt pat = %r/([\\]*)'/o strings.each do |string| string.strip! escaped = string.gsub(pat) do if $1.size % 2 == 0 "#{ $1 }''" else $& end end puts "<#{ string }> -> <#{ escaped }>" end ~ > ruby a.rb -> -> -> <1 '> -> <1 ''> <2 ''> -> <2 ''''> <3 '''> -> <3 ''''''> <4 ''''> -> <4 ''''''''> -> -> i have done this with a simple gsub - but's it's __really__ ugly... i think you may be able to find it on the list if you look... in the end it's easier to use a block and determine if you are dealing with and even or odd number of '\'s -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | URL :: http://www.ngdc.noaa.gov/stp/ | TRY :: for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done ===============================================================================