Why does re.match/re.search work, but re.findall doesn't work?
<p>I use re.match to find the string like this:</p>

<pre><code>print(re.match('''#include(\s)?".*"''', '''#include "my.h"'''))
</code></pre>

<p>then I got the result like this:</p>

<pre><code>&lt;_sre.SRE_Match object; span=(0, 15), match='#include "my.h"'&gt;
</code></pre>

<p>and then I replace match function:</p>

<pre><code>print(re.findall('''#include(\s)?".*"''', '''#include "my.h"'''))
</code></pre>

<p>the result is:</p>

<pre><code>[' ']
</code></pre>

<p>I was confused, why dosen't <code>re.findall</code> return the matched string? What's wrong with my regular expression?</p>

<p>From <code>help(re.findall)</code>:</p>

<blockquote>
  <p>Return a list of all non-overlapping matches in the string.</p>
  
  <p>If one or more capturing groups are present in the pattern, return a
  list of groups; this will be a list of tuples if the pattern has more
  than one group.</p>
  
  <p>Empty matches are included in the result.</p>
</blockquote>

<p>Your parenthesized bit, <code>(\s)</code>, is a capturing group, so <code>re.findall</code> returns a list of the captures. There&rsquo;s only one capturing group, so each item in the list is just a string, rather than a tuple.</p>

<p>You can make the group non-capturing using <code>?:</code>, i.e. <code>(?:\s)?</code>. That isn&rsquo;t very useful at that point, though, since it&rsquo;s equivalent to just <code>\s?</code>. For more flexibility &ndash; e.g. if you ever need to capture more than one part &ndash; <code>re.finditer</code> is probably the best way to go:</p>

<pre><code>for m in re.finditer(r'#include\s*"(.*?)"', '#include "my.h"'):
    print('Included %s using %s' % (m.group(1), m.group(0)))
</code></pre>

python regex