Search code examples
python-3.xregexanalysisregexp-replace

Replace $$ or more with single spaceusing Regex in python


In the following list of string i want to remove $$ or more with only one space.

eg- if i have $$ then one space character or if there are $$$$ or more then also only 1 space is to be replaced.

I am using the following regex but i'm not sure if it serves the purpose

regex_pattern = r"['$$']{2,}?"

Following is the test string list:

['1', 'Patna City $$$$ $$$$$$$$View Details', 'Serial No:$$$$5$$$$ $$$$Deed No:$$$$5$$$$ $$$$Token No:$$$$7$$$$ $$$$Reg Year:2020', 'Anil Kumar Singh Alias Anil Kumar$$$$$$$$Executant$$$$$$$$Late. Harinandan Singh$$$$$$$$$$$$Md. Shahzad Ahmad$$$$$$$$Claimant$$$$$$$$Late. Md. Serajuddin', 'Anil Kumar Singh Alias Anil Kumar', 'Executant', 'Late. Harinandan Singh', 'Md. Shahzad Ahmad', 'Claimant', 'Late. Md. Serajuddin', 'Circle:Patna City Mauja: $$$$ $$$$Khata : na$$$$ $$$$Plot :2497 Area(in Decimal):1.5002 Land Type :Res. Branch Road Land Value :1520000 MVR Value :1000000', 'Circle:Patna City Mauja: $$$$ $$$$Khata : na$$$$ $$$$Plot :2497 Area(in Decimal):1.5002 Land Type :Res. Branch Road Land Value :1520000 MVR Value :1000000']


Solution

  • About

    I am using the following regex but i'm not sure if it serves the purpose

    The pattern ['$$']{2,}? can be written as ['$]{2,}? and matches 2 or more chars being either ' or $ in a non greedy way.

    Your pattern currently get the right matches, as there are no parts present like '' or $'

    As the pattern is non greedy, it will only match 2 chars and will not match all 3 characters in $$$

    You could write the pattern matching 2 or more dollar signs without making it non greedy so the odd number of $ will also be matched:

    regex_pattern = r"\${2,}"
    

    In the replacement use a space.