title: regexp_matches returns NULL inside plpgsql function
body: <p>Given a filename of:</p>
  
  <p>xxxx/2013-02/csv/Sales_1302040000-1302050000.zip</p>
  
  <p>Can someone explain why regexp_matches returns null in this function:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION get_import_batch_date(filename text) 
  RETURNS DATE AS
  $BODY$    
  DECLARE
      matches text[];
      result date;
  BEGIN
  
      matches := regexp_matches(filename, E'Sales_(\\d{2})(\\d{2})(\\d{2})');    
      IF matches IS NOT NULL THEN
          result := format('%s-%s-%s', 2000 + matches[1]::int, matches[2], matches[3])::DATE;
          RETURN result;
      END IF;
  
      RAISE WARNING 'Unable to determine batch date from %', filename;
  
      RETURN NULL;
  
  END;
  $BODY$
    LANGUAGE plpgsql IMMUTABLE;
  </code></pre>
  
  <p>yet, works in the following anonymous function:</p>
  
  <pre><code>DO language plpgsql $$
  DECLARE
      filename text := 'xxxx/2013-02/csv/Sales_1302040000-1302050000.zip';
      matches text[];
      result date;
  BEGIN
  
      matches := regexp_matches(filename, E'Sales_(\\d{2})(\\d{2})(\\d{2})');    
      IF matches IS NOT NULL THEN
          result := format('%s-%s-%s', 2000 + matches[1]::int, matches[2], matches[3])::DATE;
          raise notice '%', result;
      END IF;
  
  END;
  $$;      
  </code></pre>
  
  <p>And the regexp_matches seems to work correctly in this query, but again, the function fails and returns null</p>
  
  <pre><code>SELECT
      regexp_matches('xxxx/2013-02/csv/Sales_1302040000-1302050000.zip', E'Sales_(\\d{2})(\\d{2})(\\d{2})'),
      get_import_batch_date('xxxx/2013-02/csv/Sales_1302040000-1302050000.zip');
  </code></pre>
  
  <p>Is there a bug in my code that I'm just not seeing (very possible and the most common answer)  Or is there something I'm failing to do here?</p>
  
  <p>I'm using PostgreSQL 9.1.6</p>
  
  <p>Just a final note: given this filename, I want the function to return a date value of 2013-02-04</p>