Possible Duplicate:
Python 3 regular expression to find multiline comment
I need some inputs on how this can be done,really appreciate your inputs,I looked at other posts but none of them matches my requirement.
How to remove line from the file in python
Remove lines from textfile with python
I need to match a multi-line comment in a file based on a input string provided.
Example:-
Lets say if the file “test.txt” has the following comment,if inputstring=”This is a test, script written” this comment needs to be deleted from the file
import os
import sys
import re
import fnmatch
def find_and_remove(haystack, needle):
pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
return re.sub(pattern, "", haystack)
for path,dirs,files in os.walk(sys.argv[1]):
for fname in files:
for pat in ['*.cpp','*.c','*.h','*.txt']:
if fnmatch.fnmatch(fname,pat):
fullname = os.path.join(path,fname)
with open(fullname, "r") as f:
find_and_remove(f, r"This is a test, script written")
Error:-
Traceback (most recent call last):
File "comment.py", line 16, in <module>
find_and_remove(f, r"This is a test, script written")
File "comment.py", line 8, in find_and_remove
return re.sub(pattern, "", haystack)
File "/usr/lib/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
TypeError: expected string or buffer
This one does it as in the request: deletes all multiline comments that contain the desired string:
Put this in a file called
program.txtThen search and replace. Just make sure the
needledoes not introduce some regex special characters.The result:
It adapts the regex in the related question
Editing the last section in your code:
Make sure that in the
needleyou escape all regex special characters e.g.().If your text contains brackets, eg,(any text)they should appear in theneedleas\(any text\)