Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python String.split使用regex忽略方括号内的内容_Python_Regex_Split - Fatal编程技术网

Python String.split使用regex忽略方括号内的内容

Python String.split使用regex忽略方括号内的内容,python,regex,split,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](?![^[]*\])”

我有一个聊天记录如下:

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](?![^[]*\])”,第6行)获取日期、时间、id、姓名、收件人、聊天室和内容。
但这不太管用。问题是,如果
内容
包含[或],则无法正确拆分行

因此,结果是:

['12-09-18','00:30:15','@966','[带空格的玩家姓名]致所有人:\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)

由于正则表达式不正确,它在聊天日志的第三行崩溃,因此分割没有生成足够的项目。

我意识到在这种情况下分割不是正确的方法,所以我最终使用了re.match:

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

尝试一下(参见),请告知此方法是否适用于您。我通过使用re.match而不是re.split解决了此问题,这更适合于类似的情况。请尽快回答下面的问题。