Python regex to edit first comment
I am writing a python script to only edit the first block of comments 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 regex to find only the first block of comments and replace it so that it looks like this:
############################
##
## Comment has
## been changed
##
############################
############################
## Don't want to change
############################
As of now, I:
editedCommentFile = re.sub(r'\#{2,150}.*?\#{2,150}.*?\s*', replString, searchedString, 1, re.DOTALL)
Unfortunately, this only matches the first line "#" and 3 characters of the next line "##". It looks like this:
############################
##
## Comment has
## been changed
##
############################ Comment to
## be changed
##
############################
############################
## Don't want to change
############################
I think I need a regex to stop pattern matching when it reaches an empty newline between the first comment block and the next. Any help would be appreciated.
source to share
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)
gives
############################
##
## Comment has
## been changed
##
############################
############################
## Don't want to change
############################
When you use \#{2,150}
then r'\#{2,150}.*?\#{2,150}'
prematurely matches
############################
##
so you get
############################
##
## Comment has
## been changed
##
############################
## Comment to
## be changed
##
############################
instead.
source to share