簡體   English   中英

Python:使用正則表達式在大文本中選擇文本

[英]Python : Using regex to select a text in a big text

s="""set(Q)
    {
information 1
    }

set(CP)
    {
information 2
    }
set(R)
    {
information 3
    }
"""

如何制作一個函數 f ,它將一個標識符作為輸入,如 (CP , R) 來選擇精確設置

示例:f("R") ------> set(R) { 信息 3 }

注意:當我使用此代碼時:它給了我:set(Q) { information 1 }

設置(CP){信息2}設置(R)

import re
def f(identifier) :

re.findall(r"set\({}\.+set)".format(identifier),s)

您必須使用 re.finditer 來獲取搜索模式的索引,然后循環遍歷字符串直到} ,同時保存您需要的內容

import re

s = """set(Q)
    {
information 1
    }

set(CP)
    {
information 2
    }
set(R)
    {
information 3
    }
set(Q)
    {
information 13
    }
"""
# print (s)


def f(identifier=''):
    var_to_return = []
    search_result = re.finditer(r'set\('+identifier+r'\)', s)
    for result in search_result:
        str_to_save = ''
        idx = result.span()[1]
        while True:
            str_to_save += s[idx]
            idx += 1
            if str_to_save[-1] == '}':
                break

        var_to_return.append(str_to_save)
    return var_to_return


print(f('Q'))

打印一個包含找到的元素的數組:

['\\n {\\n信息 1\\n }', '\\n {\\n信息 13\\n }']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM