python regex find matched string
<p>I am trying to find the matched string in a string using regex in Python. The <code>string</code> looks like this:</p>

<pre><code>band   1 # energy  -53.15719532 # occ.  2.00000000

ion      s      p      d    tot
  1  0.000  0.995  0.000  0.995
  2  0.000  0.000  0.000  0.000
tot  0.000  0.996  0.000  0.996

band   2 # energy  -53.15719532 # occ.  2.00000000

ion      s      p      d    tot
  1  0.000  0.995  0.000  0.995
  2  0.000  0.000  0.000  0.000
tot  0.000  0.996  0.000  0.996

band   3 # energy  -53.15719532 # occ.  2.00000000
</code></pre>

<p>My goal is to find the string after <code>tot</code>. So the matched string will be something like:</p>

<pre><code>['0.000  0.996  0.000  0.996', 
'0.000  0.996  0.000  0.996']
</code></pre>

<p>Here is my current code:</p>

<pre><code>pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL)
pattern.findall(string)
</code></pre>

<p>However, the output gives me:</p>

<pre><code>['1  0.000  0.995  0.000  0.995',
 '0.000  0.996  0.000  0.996',
 '1  0.000  0.995  0.000  0.995',
 '0.000  0.996  0.000  0.996']
</code></pre>

<p>Any idea of what I am doing wrong?</p>

<p>The alternative solution using <code>re.findall</code> function with specific regex pattern:</p>

<pre><code># str is your inital string
result = re.findall('tot [0-9 .]+(?=\n|$)', str)
print(result)
</code></pre>

<p>The output:</p>

<pre><code>['tot  0.000  0.996  0.000  0.996', 'tot  0.000  0.996  0.000  0.996']
</code></pre>

python regex