[英]Python and regex: split a string with parenthesis
在日志文件中,每行都有以下格式:
[date] [thread] [loglevel] [class] some text describing the event that happened.
我想遍歷日志並拆分字符串,以便獲得以下內容:['date','thread','loglevel','class','一些描述發生事件的文本。']
我很確定我需要使用re.split來做到這一點,但是我的正則表達式很糟糕。
嘗試這樣的事情:
for line in open(sys.argv[1]).xreadlines():
parts = re.split(r'[[]]',line)
任何幫助表示贊賞!
嘗試這個:
>>> log = '[date] [thread] [loglevel] [class] some text describing the event that happened.'
>>> [part.strip() for part in re.split('[\[\]]', log) if part.strip()]
['date', 'thread', 'loglevel', 'class', 'some text describing the event that happened.']
看到[或]時,字符串將被分割。 在re.split模式中,您將需要轉義這些字符。 我添加了part.strip()和if part.strip()來刪除多余的絲毫空格和空字符串
首先, \\[(.*?)\\]
將匹配括號中的任何內容。
因此,如果您想這樣做四次:
r = r'\[(.*?)\].*?' * 4
date, thread, loglevel, class = re.match(r, log).groups()
並且,得到其余:
r = r'\[(.*?)\].*?' * 4 + r'(.*)'
date, thread, loglevel, class, text = re.match(r, log).groups()
或者,如果您希望將其明確寫出:
r = r'\[(.*?)\].*?\[(.*?)\].*?\[(.*?)\].*?\[(.*?)\].*?(.*)'
……但是就我個人而言,我發現這種方式讓我頭疼。
但是,如果您在使用正則表達式時遇到困難,則簡化事情可能會更容易。 例如…
首先,找到方括號之間的所有內容:
date, thread, loglevel, class = re.findall(r'\[(.+?)\]', log)
然后在最后一個括號之后找到所有內容:
text = log.rpartition(']')[-1].lstrip()
它顯然比單個正則表達式解決方案更為冗長,而且速度可能也較慢,但是從長遠來看,如果您能夠自己理解和維護它,那么它的價值將更大。
您可以嘗試匹配字符串而不是拆分字符串。
>>> import re
>>> s = "[date] [thread] [loglevel] [class] some text describing the event that happened."
>>> m = re.findall(r'(?<=\[)[^]]*|(?<=]\s)[^\]\[]+', s)
>>> m
['date', 'thread', 'loglevel', 'class', 'some text describing the event that happened.']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.