Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for triple quote

Tags:

python

regex

What regex will find the triple quote comments (possibly multi-line) in a Python source code?

like image 440
dugres Avatar asked Sep 24 '09 14:09

dugres


People also ask

In which scenario will you prefer to use triple quotes?

Spanning strings over multiple lines can be done using python's triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes.

What is the use of triple quotes in Python?

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.


2 Answers

Python is not a regular language and cannot reliably be parsed using regex.

If you want a proper Python parser, look at the ast module. You may be looking for get_docstring.

like image 142
bobince Avatar answered Sep 23 '22 23:09

bobince


re.findall('(?:\n[\t ]*)\"{3}(.*?)\"{3}', s, re.M | re.S)

captures only text within triple quotes that are at the begging of a line and could be preceded by spaces, tabs or nothing, as python docstrings should be.

like image 32
SilentGhost Avatar answered Sep 21 '22 23:09

SilentGhost