使用正则表达式查找Python中两个已定义标记之间出现的所有多行字符串

2024-04-28 11:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图做一些意想不到的事情。我想解析一个Python代码,其中一些特定的注释行定义了我想要提取的文本或代码块。对于这个例子,我将使用两种类型的标记,一种用于代码,一种用于文本描述

#c
print ("this is the tag I used for code I want to find")
#-c

#d
"""This is the tag I used for a description I want to find"""
#-d

为什么我要这样标记代码?这是另一个问题。如果您感兴趣,请访问this SO post了解更多详细信息

现在,我一直在尝试用正则表达式捕捉这些标记,由于这是我第一次使用正则表达式,我显然没有成功。。。以下是我目前的尝试:

file = 'script.py'
with open(file, 'r') as f:
    text = f.read() 
text = read_python_script(file)

code_blocks = re.compile(r'(?s)(?<=#c\n)(.*\n)(?=#-c)')
desc_blocks = re.compile(r'(?s)(?<=#d\n)(.*\n)(?=#-d)')

code = re.findall(code_blocks, text)
desc = re.findall(desc_blocks, text)

下面是我要分析的脚本示例:

# -*- coding: utf-8 -*-
"""
Title: blablabla
Author: Mathieu

Description: Report the some measurements
"""

import time
import uuid

from database.model import TestLimit, TestResult
from util import log

#d
"""
blablabla some description
which might be multiline
"""
#-d
# Constants
#c
CONSTANT_1 = 10     # Unit
CONSTANT_2 = 2      # Unit
#-c

class Foo(Fp):
    def __init__(self, #some parameters):
        # some init

    def _run(self, #some parameters):
        #%% Section Title 1
        #%%% Sub section Title 1
        #c
        code I would like to catch
        can be multiple liens
        #-c

        
        with something.open():
            #%%% Sub section title 2
            #d
            """some description I want to catch"""
            #-d
            
            #c
            some more code I want to catch
            #-c

目前,我只得到了第一次,我不知道为什么

编辑:如前所述,我应该将表达式更改为惰性格式:

r'(?s)(?<=#c\n)(.*?)(?=\n#-c)'

这并不能完全解决这个问题,因为我仍然只是抓住了第一个问题


Tags: theto代码text标记importretitle
1条回答
网友
1楼 · 发布于 2024-04-28 11:48:45

你可以用

re.findall(r'(?s)#c\n(.*?)\n[^\S\r\n]*#-c', text)

regex demo

这里有两件事:

  • 惰性匹配.*?模式
  • [^\S\r\n]*匹配#-c之前必须使用的任何0个或多个水平空白,因为符号前可能有一些缩进

详细信息

  • (?s)-inlinere.DOTALL修饰符
  • #c-一个文本字符串
  • \n-换行符
  • (.*?)-捕获组1:任何零个或多个字符,尽可能少
  • \n-换行符
  • [^\S\r\n]*-0个或更多水平空白字符
  • #-c-一个文本字符串

相关问题 更多 >