簡體   English   中英

String.split 使用正則表達式忽略方括號內的內容

[英]String.split ignore content inside square brackets with regex

我有一個聊天記錄,如下所示:

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)但它並不完全有效。 問題是,如果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)

由於正則表達式不正確,它在聊天日志的第 3 行崩潰,因此拆分沒有產生足夠的項目。

我意識到在這種情況下拆分並不合適,所以我最終使用了 re.match:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM