returning a single instance of a regex object's contents
<p>I am writing a matching function, and I am wondering whether or not I can return only the first occurrence of a match.  Here is my code (which matches all of the instances of the url for a given line, not only the first)... this is before I attempted to select a single match:</p>

<pre><code>def file_match(line, url):
    allmatches = re.search(r'&lt;a href="(?P&lt;url&gt;.*?)"', line)
    if allmatches and allmatches.groupdict()['url'] == url:
        return allmatches.groupdict()['url']
    else: 
        return None
</code></pre>

<p>Does anyone have experience with this particular problem?
I was advised to use the '.sub' method via a regex object, but I really can't tell what I would be using for the arguments to this method.  I've tried a number of things but they all yield errors.  </p>

<p>Here is an example of one such (failed) attempts:</p>

<pre><code>def file_match(line, url):
    allmatches = re.search(r'&lt;a href="(?P&lt;url&gt;.*?)"', line)
    if allmatches and allmatches.groupdict()['url'] == url:
        return re.sub(r'&lt;a href="(?P&lt;url&gt;.*?)"', allmatches, 1)
    else: 
        return None
</code></pre>

<p>Is the problem that I am using the .search() method?</p>

<p>Any advice would be appreciated.</p>

<p>Thanks,
jml</p>
