Substituting strings with sub() method with regex
<p>I didn't want to write and ask this forum but I am stuck and the book I'm following, that supposed to be for beginners, is anything but... </p>

<p>Anyway... In the string below:  </p>

<pre><code>'Agent Alice told Agent Bob that Agent Steve was a double agent.'
</code></pre>

<p>I want to show just the first letter of the agent's first name. So what I end up with, is:</p>

<pre><code>'Agent A**** told Agent B**** that Agent S**** was a double agent.'
</code></pre>

<p>I tried using grouping, like in the book, but its not working.</p>

<pre><code>namesRegex = re.compile(r'\w?([A-Z])')
mo = namesRegex.sub(r'\1****', 'Agent Alice told Agent Bob that Agent 
Steve was a double agent.')
print(mo)
</code></pre>

<p>Also, I would welcome any recommended additional resources on this topic Thanks in advance... </p>

<p>You can use look behind <code>?&lt;=</code> syntax for this:</p>

<pre><code>namesRegex = re.compile(r'(?&lt;=Agent\s[A-Z])\w+')
mo = namesRegex.sub(r'****', 'Agent Alice told Agent Bob that Agent Steve was a double agent.')

mo
# 'Agent A**** told Agent B**** that Agent S**** was a double agent.'
</code></pre>

<p>This will replace any word character <code>\w+</code> including alpha numeric characters and underscore <code>_</code> after the pattern <code>Agent\s[A-Z]</code> with <code>****</code>. If it's not guaranteed the agent's names starts with capital letter <code>Agent\s[A-Za-z]</code> would be a less restricted option.</p>

python