使用正则表达式剥离多行python docstring

使用正则表达式剥离多行python docstring,python,regex,Python,Regex,我想使用简单的搜索和替换将所有python docstring从文件中剥离出来,以下(非常)简单的正则表达式用于单行文档字符串: 如何将其扩展到多行程序 尝试在多个位置包含\s,但均无效 由于不能使用内联s(DOTALL)修饰符,因此匹配任何字符的常用解决方法是使用具有相反速记字符类的字符类: """[\s\S]*?""" 或 或 将匹配“然后任何0+个字符,尽可能少的*?是一个懒惰的量子数,然后尾随“”有时存在非docstring的多行字符串。例如,您可能有一个跨多行扩展的复杂SQL查询。

我想使用简单的搜索和替换将所有python docstring从文件中剥离出来,以下(非常)简单的正则表达式用于单行文档字符串:

如何将其扩展到多行程序


尝试在多个位置包含
\s
,但均无效

由于不能使用内联
s
(DOTALL)修饰符,因此匹配任何字符的常用解决方法是使用具有相反速记字符类的字符类:

"""[\s\S]*?"""


将匹配
然后任何0+个字符,尽可能少的
*?
是一个懒惰的量子数,然后尾随

有时存在非docstring的多行字符串。例如,您可能有一个跨多行扩展的复杂SQL查询。下面尝试查找出现在类定义之前和函数定义之后的多行字符串

import re

input = """'''
This is a class level docstring
'''
class Article:
    def print_it(self):
        '''
        method level docstring
        '''
        print('Article')
        sql = '''
SELECT * FROM mytable
WHERE DATE(purchased) >= '2020-01-01'
'''
"""
    
doc_reg_1 = r'("""|\'\'\')([\s\S]*?)(\1\s*)(?=class)'
doc_reg_2 = r'(\s+def\s+.*:\s*)\n(\s*"""|\s*\'\'\')([\s\S]*?)(\2[^\n\S]*)'
input = re.sub(doc_reg_1, '', input)
input = re.sub(doc_reg_2, r'\1', input)
print(input)
印刷品:

class Article:
    def print_it(self):
        print('Article')
        sql = '''
SELECT * FROM mytable
WHERE DATE(purchased) >= '2020-01-01'
'''

看见
(?s)“”.*“”
“”[\s\s]*?“”
是的that@WiktorStribiżew前者起作用,即
“[\s\s]*?”
"""[\w\W]*?"""
import re

input = """'''
This is a class level docstring
'''
class Article:
    def print_it(self):
        '''
        method level docstring
        '''
        print('Article')
        sql = '''
SELECT * FROM mytable
WHERE DATE(purchased) >= '2020-01-01'
'''
"""
    
doc_reg_1 = r'("""|\'\'\')([\s\S]*?)(\1\s*)(?=class)'
doc_reg_2 = r'(\s+def\s+.*:\s*)\n(\s*"""|\s*\'\'\')([\s\S]*?)(\2[^\n\S]*)'
input = re.sub(doc_reg_1, '', input)
input = re.sub(doc_reg_2, r'\1', input)
print(input)
class Article:
    def print_it(self):
        print('Article')
        sql = '''
SELECT * FROM mytable
WHERE DATE(purchased) >= '2020-01-01'
'''