Using regex how can we remove period '.' from prefix's like Mr. and Mrs. but not from the end of the sentences in a big paragraph or more?

Viewed 35

Lang: Python. Using regex for instance if I use remove1 = re.sub('\.(?!$)', '', text), it removes all periods. I am only able to remove all periods, not just prefixes. Can anyone help, please? Just put the below text for example.

Mr. and Mrs. Jackson live up the street from us. However, Mrs. Jackson's son lives in the street parallel to us.

1 Answers

You can capture what you want to keep, and match the dot that you want to replace.

\b(Mrs?)\.

Regex demo

In the replacement use group 1 like \1

import re

pattern = r"\b(Mrs?)\."
s = ("Mr. and Mrs. Jackson live up the street from us. However, Mrs. Jackson's son lives in the street parallel to us.\n")
result = re.sub(pattern, r"\1", s)

print(result)

Output

Mr and Mrs Jackson live up the street from us. However, Mrs Jackson's son lives in the street parallel to us.
Related