user2744486
user2744486

Reputation: 161

How to use regex to replace a particular field in a formatted file

I have a file with following formatted file I need to parse

field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {
        ....
    }
    ....
}
....

I need a pre-processor in python to parse those files and delete the content of some particular fields. In the above example, the processed file will look like:

field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {}
    ....
}
....

So the preprocessor needs to locate the particular field "field_i_want_to_replace" and then delete the contents between the brackets. I'm trying to do the following but the regex can't parse the file correctly.

regex = r'(field_i_want_to_replace )\{.*?\}'
print re.sub(regex,'field_i_want_to_replace {}', file_in_string)

Is there sth wrong with the regex I'm using?

Upvotes: 0

Views: 45

Answers (1)

brianpck
brianpck

Reputation: 8254

Your . character is not matching any newlines, so it will not continue after the left curly bracket.

To change this behavior, just add the re.DOTALL flag (or re.S) as a keyword arg to your re.sub:

>>> regex = r'(field_i_want_to_replace )\{.*?\}'
>>> print re.sub(regex,'field_i_want_to_replace {}', file_in_string, flags=re.DOTALL)
field_1 {
    field_2 {
        ....
    }
    field_i_want_to_replace {}
    ....
}

Upvotes: 2

Related Questions