![](/img/trans.png)
[英]If column X contains String then find position of substring in column Y - PYTHON
[英]Find if a string contains substring python
我试图弄清楚如何在输入内的 python 中找到带有正则表达式的 substring 。 我的意思是我从用户那里得到一个输入字符串,并且我加载了 JSON 文件,在我的 JSON 文件的每个块中我有“alert_regex”,我想检查它输入中的字符串是否包含我的正则表达式。
这是我到目前为止所尝试的:
import json
from pprint import pprint
import re
# Load json file
json_data=open('alerts.json')
jdata = json.load(json_data)
json_data.close()
# Input for users
input = 'Check Liveness in dsadakjnflkds.server'
# Search in json function
def searchInJson(input, jdata):
for i in jdata:
# checks if the input is similiar for the alert name in the json
print(i["alert_regex"])
regexCheck = re.search(i["alert_regex"], input)
if(regexCheck):
# saves and prints the confluence's related link
alert = i["alert_confluence"]
print(alert)
return print('Alert successfully found in `alerts.json`.')
print('Alert was not found!')
searchInJson(input,jdata)
我希望我的正则表达式检查的是字符串是否包含“检查 flink liveness”
有 2 个可选问题: 1. 可能我的正则表达式在 i["alert_regex"] 中不正确(我已经尝试与 javascript 相同,并且有效) 2. 我的代码不正确。
我的 JSON 文件示例:
[
{
"id": 0,
"alert_regex": "check (.*) Liveness (.*)",
"alert_confluence": "link goes here"
}
]
你有两个问题。 您的所有代码都可以简化为:
import re
re.search("check (.*) Liveness (.*)", 'Check Liveness in dsadakjnflkds.server')
这将不匹配,因为:
check
将与Check
不匹配。check (.*) Liveness
如果(.)
与空字符串匹配,则 Liveness 会在check
和Liveness
之间有两个空格。你需要:
re.search("check (.*)Liveness (.*)", 'Check Liveness in dsadakjnflkds.server', flags=re.I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.