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解决了此问题,这更适合于类似的情况。请尽快回答下面的问题。