首页 > 解决方案 > 如何在 Python3 中创建一个函数以使用正则表达式从两个标记之间的字符串返回子字符串?

问题描述

我想在 Python3 中创建一个函数,它将接受 3 个输入:marker1、marker2、text 并将返回 2 个标记之间的子字符串

def findText(marker1, marker2, text):
    m = re.search(marker1(.+?)marker2, text)
    if m:
        found = m.group(1)
        print(found)  #print what was found
        return(found)

我希望当我打电话时:

print(findText("AAA", "BBB", "thisisAAAtestTextOnlyBBBxyz")) 

以显示:

testTextOnly

标签: python-3.xsubstringuser-defined-functions

解决方案


import re

def findText(marker1, marker2, text):
    search_for = r".+" + marker1 + r"(.+?)" + marker2 + ".+"
    m = re.search(search_for, text)
    if m:
        found = m.group(1)
        print(found)  #print what was found
        return(found)

findText("AAA", "BBB", "thisisAAAtestTextOnlyBBBxyz")

结果: testTextOnly


推荐阅读