如何剪切匹配的字符串

2024-09-28 23:17:45 发布

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

我想剪下匹配的线。你知道吗

我考虑使用“[m.start()”表示m in重新查找('')“获取索引。你知道吗

但我认为存在的方式比这更好。你知道吗

例如,我想在“header”和“footer”之间剪切字符串。你知道吗

str = "header1svdijfooter1ccsdheader2cdijhfooter2"
headers = ["one": "header1", "two": "header2"]
footers = ["one": "footer1", "two": "footer2"]

#I want to get ["header1svdijfooter1", "header2cdijhfooter2"]

请告诉我。你知道吗


Tags: 字符串in方式onestartheadersheaderfooter
3条回答
import re

def returnmatches(text,headers,footers):
    """headers is a list of headers
footers is a list of footers
text is the text to search"""
    for header,footer in zip(headers,footers):
        pattern = r"{}\w+?{}".format(header,footer)
        try:
            yield re.search(pattern,input_text).group()
        except AttributeError:
            # handle no match
            pass

或者:

text = "header1svdijfooter1ccsdheader2cdijhfooter2"
headers = ["header1", "header2"]
footers = ["footer1", "footer2"]

import re

matches = [re.search(r"{}\w+?{}".format(header,footer),text).group() for header,footer in zip(headers,footers) if re.search(r"{}\w+?{}".format(header,footer),text)]
import re

# as a general rule you shouldn't call variables str in python as it's a builtin function name.
str = "header1svdijfooter1ccsdheader2cdijhfooter2" 

# this is how you declare dicts.. but if you're only going to have "one"
# and "two" for the keys why not use a list?  (you need the {} for dicts).
#headers = {"one": "header1", "two": "header2"}  
#footers = {"one": "footer1", "two": "footer2"}  
delimiters = [("header1", "footer1"), ("header2", "footer2")]

results = []
for header, footer in delimiters:

    regex = re.compile("({header}.*?{footer})".format(header = header, footer = footer))

    matches = regex.search(str)
    if matches is not None:
        for group in matches.groups():
            results.append(group)

print results

无re:

str = "header1svdijfooter1ccsdheader2cdijhfooter2"
result = []
capture=False
currentCapture = ""
for i in range(len(str)):
    if str[i:].startswith("header1") or str[i:].startswith("header2"):
        currentCapture = ""
        capture=True
    elif str[:i].endswith("footer1") or str[:i].endswith("footer2"):
        capture=False
        result.append(currentCapture)
        currentCapture = ""
    if capture:
        currentCapture = currentCapture+str[i]
if currentCapture:
    result.append(currentCapture)

print result

输出:

['header1svdijfooter1', 'header2cdijhfooter2']

相关问题 更多 >