Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regular Expression to Edit First Comment

Tags:

python

regex

I am writing a python script to edit only the first comment block in my files. I have a comment block that looks like this:

############################
##
## Comment to 
## be changed
##
############################

############################
## Don't want to change
############################

I am trying to write a regular expression to only find the first comment block and replace it so it looks like this:

############################
##
## Comment has 
## been changed
##
############################

############################
## Don't want to change
############################

As of right now I have:

editedCommentFile = re.sub(r'\#{2,150}.*?\#{2,150}.*?\s*', replString, searchedString, 1, re.DOTALL)

Unfortunately this only matches the first row of '#' and the 3 characters of the next line '## '. It looks like this:

############################
##
## Comment has 
## been changed
##
############################ Comment to
## be changed
##
############################

############################
## Don't want to change
############################

I am thinking that somehow I need the regex to stop pattern matching once it reaches the blank newline between the first comment block and the next. Any help would be appreciated.

like image 325
yoloswaggins Avatar asked Jan 24 '26 00:01

yoloswaggins


1 Answers

Use \#{3,150} to require 3-or-more # characters:

import re

searchedString = '''\
############################
##
## Comment to 
## be changed
##
############################

############################
## Don't want to change
############################'''


replString = '''\
############################
##
## Comment has 
## been changed
##
############################'''

editedCommentFile = re.sub(r'\#{2,150}.*?\#{3,150}', replString, 
                           searchedString, 1, re.DOTALL)

print(editedCommentFile)

yields

############################
##
## Comment has 
## been changed
##
############################

############################
## Don't want to change
############################

When you use \#{2,150} then r'\#{2,150}.*?\#{2,150}' prematurely matches

############################
##

which is why you would get

############################
##
## Comment has 
## been changed
##
############################
## Comment to 
## be changed
##
############################

instead.

like image 130
unutbu Avatar answered Jan 26 '26 15:01

unutbu