简体   繁体   English

使用 re.sub 替换模式

[英]Use re.sub to replace a pattern

I have a text file look like this :我有一个如下所示的文本文件:

6-9 867-873 Social  Project[4]  
6-10    874-882 Contract    Project[4]  
6-11    883-887 Core    Project[4]  
6-12    888-889 (   _   
6-13    889-892 SCC Project 

I was trying to replace all the "project" and "project[x]" to o By using the following code:我试图将所有“项目”和“项目 [x]”替换为 o 通过使用以下代码:

newline2 = re.sub(r"Project\[\d+\]","o",newline)

Only the Project[x] got replaced to o, not the "project", is there anyway I can replace the "Project" too?只有 Project[x] 被替换为 o,而不是“项目”,无论如何我也可以替换“项目”吗?

You can make the last part optional using a group and ?您可以使用组和? :

re.sub(r'Project(\[\d+\])?', 'o', newline)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM