String.split使用正则表达式忽略方括号内的内容

时间:2018-12-30 23:43:51

标签: python regex split

我的聊天记录如下:

12-09-18 00:31:40   @966 [playerwithoutspaces] to TEAM: Hello all
12-09-18 00:32:11   @966 [playerswith[inname] to ALL:   Helloall
12-09-18 00:30:15   @966 [player name with spaces] to ALL:  Hello all]

我正在尝试使用re.split("""[\s\t](?![^[]*\])""", line, 6)获取日期,时间,id,名称,收件人,聊天和内容 但这并不完全有效。问题是,如果content包含[或],则无法正确分割行。

结果是:

['12-09-18', '00:30:15', '@966', '[player name with spaces] to ALL:\tHello all]', '']

应该在什么时候出现:

['12-09-18', '00:30:15', '@966', '[player name with spaces]', 'to', 'ALL:', '\tHello all]']

我只是尝试了一段时间以匹配[],但这没用。

我忘了提到内容前面带有制表符\ t或空格\ s,因此内容会有所不同。

以下是要求的代码:

file = open("chatlog.txt", encoding="ANSI")
...
async def main():
    for line in file.readlines():
        await handle_chatlog_line(line)

async def handle_chatlog_line(line):
    print(re.split("""[\s\t](?![^[]*\])""", line, 6))
    date, time, ingame_client_id, client_name, irrelevant, chat, content = re.split("""[\s\t](?![^[]*\])""", line, 6)

由于正则表达式不正确,因此在聊天日志的第三行崩溃,因此拆分产生的项目不足。

1 个答案:

答案 0 :(得分:0)

我意识到在这样的情况下分拆是不可能的,所以我最终使用了re.match:

match = re.match("(\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\s+(@\d+) \[(.+)\] to (TEAM|ALL):\s+(.+)",line)