From: Chai Muang thong Date: 2008-12-02T23:35:48+09:00 Subject: Re: regexp problem Constantine Karnacevych wrote: > Brian Candler wrote: > > def match_pairs s, l, r > d, o, e = 0, [], '(' + Regexp.escape(l) + '|' + Regexp.escape(r) + > ')' > while m = s =~ /#{e}/ do > $1 == l ? (o << "" if 1 === d += 1) : d -= 1 > o[o.length - 1] += o.last.empty? ? $1 : $` + $1 > s = $' > end > o > end > > str = "<> <>>>>> <> or <>>>>>" > p match_pairs str, "<<", ">>" > > => ["<> <>>>>>", "<>", "<>>>>>"] > > p match_pairs str, "<", ">" > => ["<> <>>>>>", "", "<>", "< <>>>>>"] > > str = '{p1 {p2} {p3 {p4}}} {p5} or {p6 {p7 {p8}}}' > p match_pairs str, '{', '}' > > => ["{p1 {p2} {p3 {p4}}}", "{p5}", "{p6 {p7 {p8}}}"] -------------- Thank you very much Brian. It works fine as long as an incoming string is valid. In other words, if the string has extra pair to the left, it will return wrong result. For example a string "Test or < correct tag" will return ["<<"] instead of [""]. Anyway, I have solved the problem by implementing a method to handle this instead of using only regexp. Thank you again. Chai -- Posted via http://www.ruby-forum.com/.