python-3.x - 如何在 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
解决方案
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
推荐阅读
- javascript - 在父类javascript中选择标签
- windows - 远程系统服务重启
- amazon-web-services - ElasticBeanstalk `eb setenv` - 应用程序重启
- xamarin - 你如何正确地继承 MvxCollectionViewSource?
- javascript - 创建文件并保存到变量 NodeJS
- c# - 是否允许嵌套模板化控件
- kubernetes - Pod 预设不适用于 minikube
- mysql - SQL:将一行中的所有数据相加
- windows - 使用 Powershell 脚本从批量 Windows 服务器的默认域策略中提取安全设置
- ruby - Ruby - 使用注入的阶乘/组合