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>

<pre><code>import re

string = "Some text"

replace = {'St': 'Saint', 'St.': 'Saint', 'st': 'Saint', 'st.': 'Saint'}
replace = dict((re.escape(k), v) for k, v in replace.iteritems())
pattern = re.compile("|".join(replace.keys()))
for text in string.split():
    text = pattern.sub(lambda m: replace[re.escape(m.group(0))], text)
</code></pre>

<p>This should work I guess, please check.
<a href="http://stackoverflow.com/questions/6116978/python-replace-multiple-strings">Source</a></p>

python regex