删除python中特殊字符之间的字符串

时间:2016-08-30 09:34:59

标签: python regex

我有类似这样的字符串

mystring = "CBS Network Radio Panel;\ntitle2 New York OCT13W4, Panel Weighting;\n*options; mprint ls=max mprint;\n\n****************************************out; asd; ***hg;"

我想删除*和之间的字符串; 输出应该是

"CBS Network Radio Panel;\ntitle2 New York OCT13W4, Panel Weighting;\ mprint ls=max mprint;\n\n asd;"

我试过这段代码

re.sub(r'[\*]*[a-z]*;', '', mystring)

但它不起作用。

1 个答案:

答案 0 :(得分:3)

您可以使用

re.sub(r'\*[^;]*;', '', mystring)

请参阅Python demo

import re
mystring = "CBS Network Radio Panel;\ntitle2 New York OCT13W4, Panel Weighting;\n*options; mprint ls=max mprint;\n\n****************************************out; asd; ***hg;"
r = re.sub(r'\*[^;]*;', '', mystring)
print(r)

输出:

CBS Network Radio Panel;
title2 New York OCT13W4, Panel Weighting;
 mprint ls=max mprint;

 asd;

r'\*[^;]*;'模式与文字*匹配,后跟除;以外的零个或多个字符,然后是;