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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With