Skip to main content
 首页 » 编程设计

python之Python 3 中的正则表达式

2024年08月20日38Terrylee

我是新来的,刚开始在我的 python 代码中使用正则表达式。我有一个字符串,里面有 6 个逗号。其中一个逗号位于两个引号之间。我想去掉引号和最后一个逗号。

输入:

string = 'Fruits,Pear,Cherry,Apple,Orange,"Cherry,"' 

我想要这个输出:

string = 'Fruits,Pear,Cherry,Apple,Orange,Cherry'          

我的代码的输出:

string = 'Fruits,Pear,**CherryApple**,Orange,Cherry' 

这是我在 python 中的代码:

if (re.search('"', string)): 
    matches  = re.findall(r'\"(.+?)\"',string); 
    matches1 = re.sub(",", "", matches[0]); 
    string   = re.sub(matches[0],matches1,string); 
    string   = re.sub('"','',string); 

我的问题是,我想给出一个条件,即代码仅适用于最后一位(“Cherry,”),但不幸的是它会影响中间的其他词(Cherry、Apple),其文本与一个在引号之间!这导致逗号数量减少(从 6 个减少到 4 个),因为它合并了两个字段(Cherry、Apple),我想留下 5 个逗号。

fullString = '2000-04-24 12:32:00.000,22186CBD0FDEAB049C60513341BA721B,0DDEB5,COMP,Ch‌​erry Corp.,DE,100,0.57,100,31213C678CC483768E1282A9D8CB524C,365.0‌​0000,business,acquis‌​itions-mergers,acqui‌​sition-bid,interest,‌​acquiree,fact,,,,,,,‌​,,,,,,acquisition-in‌​terest-acquiree,Cher‌​ry Corp. Gets Buyout Offer From Chairman President,FULL-ARTICLE,B5569E,Dow Jones Newswires,0.04,-0.18,0,0,1,0,0,0,0,1,1,5,RPA,DJ,DN2000042400‌​0597,"Cherry Corp. Gets Buyout Offer From Chairman President,"\n' 

非常感谢

请您参考如下方法:

对于您的任务,您不需要正则表达式,只需使用replace:

string = 'Fruits,Pear,Cherry,Apple,Orange,"Cherry,"' 
new_string = string.replace('"').strip(',')