Python Regular Expression Matching Multiline Comments and Docstrings

Python allows single line / multiline comments and docstrings. In this article you can find regular expressions how to search and replace multiline comments / docstrings in PyCharm.

On this link you can find PyCharm Regular Expression Syntax Reference

In order to start the search / replace menu:

  • Press CTRL + R to open the search and replace pane
  • Check Regex checkbox
  • Enter a search string in the top field
  • Escape the metacharacters like: .[{()\^$|?*+ - so searching for ? in the code should be done by \?

More info on this link: Find and replace a string using regular expressions

Match Python single line comment

Selecting single python comments can be done by this regex:

#.*\n

Now you can replace it by empty string if you want to remove the comments and make your code more readable. You can find demo how the code is much more readable after cleaning the comments:

Halite III PyCharm integration and import of custom class - at the middle there is cleaning of the code from the all comments.

Match Python single and multi-line docstrings

Now to the main topic of the article - how to match only doc comments with Python like:

single docstring

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root

multi-line docstring

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

There are several regex for matching single and multi-line docstrings like(the option should work in the most cases with some exceptions):

  • option one
"""[\s\S]*?"""
  • option two
"""[\d\D]*?"""
  • option three
"""[\w\W]*?"""
  • option four
(['"])\1\1[\d\D]*?\1{3}
  • option five
([^:]"""[^\(]*)"""

PyCharm code inspection for broken and missing docstrings

You can use also the PyCharm code inspection in order to find undocumented methods/classes in your code. This can be done by:

  • Settings (File/Settings) - CTRL + ALT + S
  • Editor
  • Inspections
  • Search for doc strings
  • Enable feature: Missing or empty docstrings
    • This inspection detects lack of docstring and an empty docstring.