查找字符串是否包含子字符串python

时间:2019-10-27 16:24:02

标签: python regex

我试图弄清楚如何在输入中的python中使用regex查找子字符串。 我的意思是,我从用户那里得到一个输入字符串,并且我加载了一个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活动性”时,我才希望我的正则表达式检查什么

有2个可选问题: 1.也许我的正则表达式在i [“ alert_regex”]内部不正确(我已经尝试使用javascript来实现同一个效果了) 2.我的代码不正确。

我的JSON文件的示例:

[
    {
        "id": 0,
        "alert_regex": "check (.*) Liveness (.*)",
        "alert_confluence": "link goes here"
    }
]

1 个答案:

答案 0 :(得分:0)

您有两个问题。您所有的代码都可以简化为:

import re
re.search("check (.*) Liveness (.*)", 'Check Liveness in dsadakjnflkds.server')

这不匹配,因为:

  1. 您需要在搜索中设置“不区分大小写”,因为check将与Check不匹配。
  2. 如果check (.*) Liveness与空字符串匹配,
  3. checkLiveness(.)之间以两个空格结尾。

您需要:

re.search("check (.*)Liveness (.*)", 'Check Liveness in dsadakjnflkds.server', flags=re.I)