Search code examples
pythonpython-re

AWS Lambda - re.sub in Python - remove Brackets at end of line


I need to convert Hive DDL's to Redshift DDL. I am utilizing re.sub in my code to perform conversion. I am unable to substitute ')' at the end of line.

Eg:-

"ci_stage" : "varchar(30))
"target_manager_id" : "bigint)

Desired output:-

"ci_stage" : "varchar(30)"
"target_manager_id" : "bigint"

I have tried:

modified_line113 = re.sub('[)]$','"', modified_line112)
modified_line113 = re.sub(r"\)$", '"', modified_line112)

They are not working. What is the easiest way to remove character ")" at end of line?


Solution

  • Your pattern uses an anchor to assert the end of the string, so you need to add the multi line flag re.M to re.sub for multiple replacements.

    import re
    
    modified_line112 = """"ci_stage" : "varchar(30))
    "target_manager_id" : "bigint)"""
    
    modified_line113 = re.sub(r"\)$", '"', modified_line112, 0, re.M)
    print(modified_line113)
    

    Output

    "ci_stage" : "varchar(30)"
    "target_manager_id" : "bigint"