1

I am trying to locate the following header in a list of files and replace it with my own.

/*************************************************************************************
 * Company: XXX
 * File Name: myfile1.c
 * Author: MyName
 * Date: 30/12/2011
 * Operating Environment: XXX
 * Compiler with Version Number:
 * Description: This file contains an array which returns a structure having API characteristics.
 * Version:
 ***********************************************************************************/

Basically I'm trying to write a python program to traverse a list of directories and do the string replacement in all of files. Following is the code for my program:

import sys
import os
import re
correctlicheader = r'''
/* <MY-HEADER>
 *
 */
'''

def changelic():
   startdir = sys.argv[1]
   for root, dirs, files in os.walk(startdir):
      for file in files:
         actualfilename =  os.path.join(root, file)
         print("Reading file: %s" %(actualfilename))
         f = open(actualfilename, 'r')
         read_data = f.read()             
         #try replacing the incorrect header
         p = re.compile("<MY-REGULAREXPRESSION-HERE>")
         changed_data = p.sub(correctlicheader, read_data, 1)
         f.close()
         f= open(actualfilename, 'w')
         f.write(changed_data)
         f.close()
    print("End")

if __name__ == '__main__':
   changelic()

The problem is not getting 'MY-REGULAREXPRESSION-HERE' right. I tried

p = re.compile("/\*[\*]*\r\n[ *[a-zA-Z0-9:/\.]+\r\n]*\*/")

and various permutations of the above. But I keep getting

matched = p.match(read_data)
None

Any suggestions to replace 'MY-REGULAREXPRESSION-HERE'? Also, is there any better method to do the same without open(read-mode)-close-open(write-mode)-write ?

4
  • 1
    Other people know ostermiller.org/findcomment.html Commented Jan 31, 2013 at 17:08
  • 1
    Specifically /\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ works in my test of your code. I hope the code is backed up or under source control. Commented Jan 31, 2013 at 17:16
  • @sotapme combine those two comments into an answer. That's clearly what the OP is looking for. Commented Jan 31, 2013 at 17:21
  • I'm old fashioned, I was trying to save webspace. Fair point though. Commented Jan 31, 2013 at 17:27

1 Answer 1

1

http://ostermiller.org/findcomment.html has the regexps for finding c++ comments.

Changing <MY-REGULAREXPRESSION-HERE> to /\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ will do the right thing.

I've run your code on my machine and it does as one would expect.

Thanks to @Wilduck for the push. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.