Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id 838F231E98A for ; Fri, 6 Jan 2012 03:21:36 -0400 (AST) Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1Rj47K-0007E3-Dl for pgsql-bugs@postgresql.org; Fri, 06 Jan 2012 07:21:36 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id q067LJAF003499; Fri, 6 Jan 2012 02:21:19 -0500 (EST) To: code@phaedrusdeinus.org cc: pgsql-bugs@postgresql.org Subject: Re: BUG #6381: Incorrect greediness behavior in certain regular expressions In-reply-to: References: Comments: In-reply-to code@phaedrusdeinus.org message dated "Fri, 06 Jan 2012 00:32:17 +0000" Date: Fri, 06 Jan 2012 02:21:19 -0500 Message-ID: <3498.1325834479@sss.pgh.pa.us> From: Tom Lane X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201201/39 X-Sequence-Number: 32106 code@phaedrusdeinus.org writes: > This, more complex/complete version, matches greedily, which is incorrect: > =# select regexp_matches('http://blahblah.com/asdf', > 'http(s?)(:|%3a)(//|%2f%2f)(.*?)(/|%2f|$)'); > regexp_matches > -------------------------------- > {"",:,//,blahblah.com/asdf,""} I do not believe this is a bug; the RE code appears to me to be following its specification, as per the detailed rules in section 9.7.3.5: http://www.postgresql.org/docs/9.1/static/functions-matching.html#POSIX-MATCHING-RULES Specifically, the regex as a whole is considered greedy because the first subpart with a greediness attribute is the (s?) piece, and the ? quantifier is greedy. Therefore, the regex as a whole matches the longest possible string, which in this case will be up to the end of the input. It's true that the (.*?) subpart is non-greedy, but that only affects how much of the overall match length can get assigned to that subpart relative to other subparts, and in this case there is no flexibility to assign it more or less of the match once the total match length is determined. The reason your second case "works" as you expect is that there's no way for it to match anything beyond the last slash: > select regexp_matches('http://blahblah.com/asdf', > 'http(s?)(:|%3a)(//|%2f%2f)(.*?)(/|%2f)'); > regexp_matches > -------------------------- > {"",:,//,blahblah.com,/} There's only one possible match here, independently of whether the (.*?) portion is greedy or not. With this example, you could get the results you're after by using the non-greedy ?? operator for the first subpart: regression=# select regexp_matches('http://blahblah.com/asdf', 'http(s??)(:|%3a)(//|%2f%2f)(.*?)(/|%2f|$)'); regexp_matches -------------------------- {"",:,//,blahblah.com,/} although I cannot tell whether that generalizes to your real problem. regards, tom lane