From: Martin DeMello Date: 2001-12-17T10:16:10+09:00 Subject: [ruby-talk:28721] Scanning for delimited substrings I need to scan a string for delimited substrings, and return an array (as in String#scan) broken into the substrings and the bits between them. For example, "one <> three <> five six <>" scanned for ("<<",">>") should return ["one ", "<>", " three ", "<>", " five six ", "<>"]. The task is made somewhat easier by the fact that delimiters are strictly not nested ("foo <> quux>>" should return ["foo ", "<>", " quux"]) Anyway, I have the following (working, afaik) code; I was just wondering if there was a better (faster and/or more elegant) way to do it. (Frinstance a straight call to scan (and a few flattens and compacts) might do it, but I couldn't work out the regexp). class String def delimit_scan(l,r) a = [] s = self.dup m = "(#{Regexp.quote(l)}[^\n]*?#{Regexp.quote(r)})" while s s =~ m if ($&) a << $` << $& s = $' else a << s s = nil end end a end end a = "the <> <> jumps over <> lazy>> dog." puts a.delimit_scan("<<",">>") --- which returns --- the <> <> jumps over <> lazy>> dog. -------------------- Also, I left out nested delimiters because I don't need them, and I couldn't think of a clean way to add them in without slowing things down, but if there's a more general method that trivially handles both cases I'd like to see it. -- Martin DeMello