Regular Expression to replace some dots with commas in customers' comments
<p>I need to write a Regular Expression to replace <code>'.'</code> with <code>','</code> in some patients' comments about drugs. They were supposed to use comma after mentioning a side effect, but some of them used dot. for example: </p>

<pre><code>text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache.  I suffered. she suffered. she told I should change it."
</code></pre>

<p>I wrote a regular expression code to detect one word (such as, headache) or two words (such as, bad dream)  surround by  two dots:</p>

<h1>detecting a word surrounded by two dots:</h1>

<pre><code>text=  re.sub (r'(\.)(\s*\w+\s*\.)',r',\2 ', text )
</code></pre>

<h1>detecting two words surrounded by two dots:</h1>

<pre><code>text =  re.sub (r'(\.)(\s*\w+\s\w+\s*\.)',r',\2 ', text11 )
</code></pre>

<p>This is the output:</p>

<pre><code>the drug side-effects are: night mare, nausea,  night sweat.  bad dream, dizziness,  severe headache.   I suffered, she suffered.  she told I should change it.
</code></pre>

<p>But it should be: </p>

<pre><code>the drug side-effects are: night mare, nausea,  night sweat,  bad dream, dizziness,  severe headache.   I suffered. she suffered.  she told I should change it.
</code></pre>

<p>My code did not replace <code>dot</code> after <code>night sweat to ','</code>. I addition, <code>if a sentence starts with a subject pronoun (such as I and she) I do not want to change dot to comma after it, even if it has two words (such as, I suffered)</code>. I do not know how to add this condition to my code. </p>

<p>Any suggestion? Thank you !</p>

<p>You can use the following pattern:</p>

<pre><code>\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$)
</code></pre>

<p>This matches a dot, then captures one or two words where the first one is none of your mentioned pronouns (you will need to expand that list most likely). This has to be followed by a character that is neither a word character nor a space (e.g. <code>.</code> <code>!</code> <code>:</code> <code>,</code>) or the end of the string.</p>

<p>You will then have to replace it with <code>,\1</code></p>

<p>In python</p>

<pre class="lang-py prettyprint-override"><code>import re
text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache.  I suffered. she suffered. she told I should change it."
text = re.sub(r'\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$)', r',\1', text, flags=re.I)
print(text)
</code></pre>

<p>Outputs</p>

<pre><code>the drug side-effects are: night mare, nausea, night sweat, bad dream, dizziness, severe headache.  I suffered. she suffered. she told I should change it.
</code></pre>

<p>This is likely not absolutely failsafe and you might have to expand the pattern for some edge cases.</p>

python regex