查找字符串是否包含子字符串python
我试图弄清楚如何在输入中找到python中带有正则表达式的子字符串。 我的意思是,我从用户那里得到一个输入字符串,我加载了一个JSON文件,在JSON文件的每个块中,我都有“alert_regex”,我想检查一下,输入中的字符串包含我的regex 这就是我迄今为止所尝试的:查找字符串是否包含子字符串python,python,regex,Python,Regex,我试图弄清楚如何在输入中找到python中带有正则表达式的子字符串。 我的意思是,我从用户那里得到一个输入字符串,我加载了一个JSON文件,在JSON文件的每个块中,我都有“alert_regex”,我想检查一下,输入中的字符串包含我的regex 这就是我迄今为止所尝试的: import json from pprint import pprint import re # Load json file json_data=open('alerts.json') jdata = json.loa
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)
我希望正则表达式只在字符串包含“check flink liveness”时进行检查
有两个可选问题:
1.也许我的正则表达式在我[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不匹配。
检查。*如果需要,则活动性在检查和活动性之间有两个空格。匹配空字符串。
你需要:
re.search("check (.*)Liveness (.*)", 'Check Liveness in dsadakjnflkds.server', flags=re.I)
检查字符串x是否包含子字符串y的方法是检查x中的y。不需要任何正则表达式。您应该包含一个最小的jdata示例,其中的项应该与字符串匹配。您的正则表达式模式与输入示例不匹配。应该有吗?您是否在一个在线python风格的正则表达式测试仪中尝试过其他方法?