Python 如何将一个字符串解析为两个字符串
如何将形式为“some words[branch](https://url)的字符串解析为两个字符串:“some words[branch]”和“https://url" 在我的例子中,这是关于“托马斯·莫加被推到分支[大师]()”的部分 我的代码:Python 如何将一个字符串解析为两个字符串,python,Python,如何将形式为“some words[branch](https://url)的字符串解析为两个字符串:“some words[branch]”和“https://url" 在我的例子中,这是关于“托马斯·莫加被推到分支[大师]()”的部分 我的代码: headers = { "Content-Type": "application/json" } body = json.loads(event['body']) pa
headers = {
"Content-Type": "application/json"
}
body = json.loads(event['body'])
payload = {
"payload": {
"summary": body['sections'][0]['activityTitle'],
"severity": "critical",
},
和json:
"body":
"{\"sections\":
[
{\"activityTitle\":\"Thomas Moga pushed to branch [master](https://gitlab.com/thomas.moga/my-project/commits/master)\"}
]
}
您可以使用regex(re
module)来解决它
import re
text="Thomas Moga pushed to branch [master](https://gitlab.com/thomas.moga/my-project/commits/master)"
match = re.search(r'(.*?\])\s*\((.*?)\)', text)
if match:
message = match.group(1)
url = match.group(2)
print (message)
print(url)
输出:
托马斯·莫加(Thomas Moga)被推到分支机构[大师]
此代码假定消息的格式为
[]()
我认为正则表达式非常复杂(但这是我自己的观点),因此,下面是一个不导入任何模块的示例:
s=“托马斯·莫加被推到分支机构[主机](https://gitlab.com/thomas.moga/my-project/commits/master)"
短语url=s.split(“(”)#在此处拆分字符串^^
url=url.strip(“)”#去掉右括号^
印刷品(短语)
打印(url)
输出:
Thomas Moga被推到分支机构[主机]
https://gitlab.com/thomas.moga/my-project/commits/master
我想你是在问:我如何解析“一些单词[branch]形式的字符串(https://url)“
分为两个字符串:“一些单词[分支]”
和”https://url“
@jarmod是的,这正是我的意思!更新您的问题,以澄清您的要求,这将重新打开问题。