如何在Python中使用正则表达式删除带有特殊字符串的字符?

2024-05-16 11:42:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图清理日志,我想删除一些特殊的字符串

示例:

%/h >  %/h Current value over threshold value
Pg/S >  Pg/S Current value over threshold value
Pg/S >  Pg/S  No. of pages paged in exceeds threshold
MB <  MB   min. avg. value over threshold value

我试过使用一些模式,但似乎不起作用。你知道吗

re.sub(r'\w\w\/\s>\s\w','',text)

我有什么好办法去掉这个特殊的图案吗?你知道吗

我要删除…/…>;../。。。你知道吗

我希望我的输出只包含有用的单词。你知道吗

   Current value over threshold value
   No. of pages paged in exceeds threshold
   min. avg. value over threshold value

谢谢你的建议!你知道吗


Tags: ofno字符串inthresholdvaluembpages
3条回答

根据您试图匹配的模式,似乎您总是知道字符串的位置。实际上,您可以不使用regex来实现这一点,只需使用split切片即可获得感兴趣的部分。最后,使用join返回到字符串,以获得最终结果。你知道吗

以下结果将执行以下操作:

s.split()-在空格上拆分,创建一个列表,其中每个单词都是列表中的一个条目

[3:]-从第四个位置(0索引)开始对列表进行切片

' '.join()-将转换回字符串,在列表中的每个元素之间放置一个空格

演示:

s = "%/h >  %/h Current value over threshold value"
res = ' '.join(s.split()[3:])

输出:

Current value over threshold value

假设文件的结构为:

[special-string] [< or >] [special-string] [message]

那么这就行了:

>>> rgx = re.compile(r'^[^<>]+[<>] +\S+ +', re.M)
>>>
>>> s = """
... %/h >  %/h Current value over threshold value
... Pg/S >  Pg/S Current value over threshold value
... Pg/S >  Pg/S  No. of pages paged in exceeds threshold
... MB <  MB   min. avg. value over threshold value
... """
>>>
>>> print(rgx.sub('', s))
Current value over threshold value
Current value over threshold value
No. of pages paged in exceeds threshold
min. avg. value over threshold value

这是一个相对较长的正则表达式,但它完成了任务。你知道吗

[%\w][\/\w]\/?[\/\s\w]\s?\<?\>?\s\s[\w%]\/?[a-zA-Z%]\/?[\w]?\s\s?\s?

演示:https://regex101.com/r/ayh19b/4

或者你可以这样做:

^[\s\S]*?(?=\w\w(?:\w|\.))

演示:https://regex101.com/r/ayh19b/6

相关问题 更多 >