how to find match first word in string with regex in python
<p>I want to match the word <code>'St' or 'St.' or 'st' or 'st.'</code> BUT only in first word of a string.
For example ' St. Mary Church Church St.' - should find ONLY first St. </p>

<ul>
<li>'st. Mary Church Church St.' - should find ONLY 'st.' </li>
<li>'st Mary Church Church St.' - should find ONLY 'st'</li>
</ul>

<p>I want to eventually replace the first occurence with 'Saint'.</p>

<p>I have literally spent hours trying to find a regex that will match this problem so i have tried myself first and i now for some of you it will be easy!</p>

<p>Regex <code>sub</code> allows you to define the number of occurence to replace in a string. </p>

<p>i.e. : </p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; s = "St. Mary Church Church St."
&gt;&gt;&gt; new_s = re.sub(r'^(St.|st.|St|st)\s', r'Saint ', s, 1) # the last argument defines the number of occurrences to be replaced. In this case, it will replace the first occurrence only.
&gt;&gt;&gt; new_s
'Saint Mary Church Church St.'
&gt;&gt;&gt; 
</code></pre>

<p>Hope it hepls. </p>

python regex