Search code examples
pythonpython-re

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:

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?


Solution

  • You can make the last part optional using a group and ?:

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