Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9095731
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T23:40:44+00:00 2026-06-16T23:40:44+00:00

Possible Duplicate: Python 3 regular expression to find multiline comment I need some inputs

  • 0

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
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T23:40:45+00:00Added an answer on June 16, 2026 at 11:40 pm

    This one does it as in the request: deletes all multiline comments that contain the desired string:

    Put this in a file called program.txt

    /*
     * This is a test, script written
     * This is a comment line
     * Multi-line comment
     * Last comment
     *
     */
    
    some code
    
    /*
     * This is a comment line
     * And should 
     *     not be removed
     *
     */
    
    more code
    

    Then search and replace. Just make sure the needle does not introduce some regex special characters.

    import re
    
    def find_and_remove(haystack, needle):
        pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
        return re.sub(pattern, "", haystack)
    
    # assuming your program is in a file called program.txt
    program = open("program.txt", "r").read()
    
    print find_and_remove(program, r"This is a test, script written")
    

    The result:

    some code
    
    /*
     * This is a comment line
     * And should 
     * not be removed
     *
     */
    
    more code
    

    It adapts the regex in the related question

    Editing the last section in your code:

    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)
                    # put all the text into f and read and replace...
                    f = open(fullname).read()
                    result = find_and_remove(f, r"This is a test, script written")
    
                    new_name = fullname + ".new"
                    # After testing, then replace newname with fullname in the 
                    # next line in order to replace the original file.
                    handle = open(new_name, 'w')
                    handle.write(result)
                    handle.close()
    

    Make sure that in the needle you escape all regex special characters e.g. (). If your text contains brackets, eg, (any text) they should appear in the needle as \(any text\)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Python Regular Expression Matching: ## ## I already asked this question, but
Possible Duplicate: Reversing a regular expression in python I think I ran into a
Possible Duplicate: Python or Ruby Interpreter on iOS I just discovered this apps pypad
Possible Duplicate: Python rounding error with float numbers python maths is wrong I can't
Possible Duplicate: How to detect a floating point number using a regular expression How
Possible Duplicate: Python “extend” for a dictionary I know that Python list can be
Possible Duplicate: matching unicode characters in python regular expressions Using re.findall(r'\w+', ip) on Fältskog
Possible Duplicate: Matching Nested Structures With Regular Expressions in Python I am trying to
Possible Duplicate: How to print date in a regular format in Python? I would
Possible Duplicate: Python list subtraction operation In Python you can concatenate lists like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.