Skip to main content
 首页 » 编程设计

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

2025年05月04日21arxive

我正在尝试清理日志,我想删除一些特殊字符串

例子:

%/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 

谢谢你的想法!

请您参考如下方法:

假设文件的结构是:

[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