Optional dot in regex
Question: Say I want to replace all the matches of `Mr.` and `Mr` with `Mister`.

I am using the following regex: `\bMr(\.)?\b` to match either `Mr.` or just
`Mr`. Then, I use the [`re.sub()`
method](https://docs.python.org/2/library/re.html#re.sub) to do the
replacement.

What is puzzling me is that it is replacing `Mr.` with `Mister.`. Why is this
keeping the dot `.` at the end? It looks like it is not matching the `Mr\.`
case but just `Mr`.

    
    
    import re
    s="a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody."
    re.sub(r"\bMr(\.)?\b","Mister", s)
    

Returns:

    
    
    'a rMr. Nobody Mister. Nobody is Mister Nobody and Mra Nobody.'
    

I also tried with the following, but also without luck:

    
    
    re.sub(r"\b(Mr\.|Mr)\b","Mister", s)
    

My desired output is:

    
    
    'a rMr. Nobody Mister Nobody is Mister Nobody and Mra Nobody.'
                         ^                              ^
                         no dot            this should be kept as it is
    


Answer: I think you want to capture `'Mr'` followed by _either a`'.'` **or** a word
boundary_:

    
    
    r"\bMr(?:\.|\b)"
    

In use:

    
    
    >>> import re
    >>> re.sub(r"\bMr(?:\.|\b)", "Mister", "a rMr. Nobody Mr. Nobody is Mr Nobody and Mra Nobody.")
    'a rMr. Nobody Mister Nobody is Mister Nobody and Mra Nobody.'
    

