【问题标题】:Return specific character group in list of long strings返回长字符串列表中的特定字符组
【发布时间】:2023-02-25 04:31:42
【问题描述】:

我在这里看到的答案都不满足我的条件。我需要遍历此字符串列表中的每个字符串并返回特定模式。例如,我需要返回所有日期、时间和主机名。我的想法是用板条箱创建单个列表,以便我以后可以构建数据框。我已经创建了 RegEx 模式,但我在迭代时遇到了问题。

以下是字符串列表的示例:

logs = [
            "Feb 24 2023 20:37:42 somedomain.com Label=Risk_Level cs5=Low cs2Label=Policy act=Deny shost=VD-DONALD dntdom=disney\\\\ ",
            "Feb 24 2023 20:46:10 somedomain.com Label=Risk_Level cs5=High cs2Label=Policy act=Terminate shost=VD-MICKEY dntdom=disney\\\\ ",
            ]

这是用于捕获日期、时间和主机的 RegEx:

date = ''.join(re.findall('\w{3}\s\d{2}\s\d{4}',logs))
timestamp = ''.join(re.findall('\d{2}:\d{2}:\d{2}',logs)[0])
target_host = ''.join(re.findall('shost=([^\s]+)',logs))

这是我失败的尝试。我不断收到TypeError: expected string or bytes-like object。我明白这个错误,但我不知道如何解决它。

尝试 1:

date_list = []
for log in logs:
    for date in log:
        date_list.append(date)
print(date_list)

尝试 2:

for log in logs:
    for log_item in log:
        if date in log_item:
            print(date)

预期结果:

dates_list = ['Feb 24 2023', 'Feb 24 2023']
timestamp_list = ['20:37:42', '20:46:10']
host_list = ['VD-DONALD','VD-MICKEY']

【问题讨论】:

  • re.findall 接受一个字符串而不是一个列表作为输入

标签: python


【解决方案1】:

遍历 list 中的每个元素,并对每个元素调用 re.search 以从每个字符串中提取匹配值。

for log in logs:
    date = re.search('w{3}sd{2}sd{4}',log).group()
    timestamp = re.search('d{2}:d{2}:d{2}',log).group()
    target_host = re.search('shost=([^s]+)',log).group()
    print(date, timestamp, target_host)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2019-12-23
    相关资源
    最近更新 更多