Home > Mobile >  Replace $$ or more with single spaceusing Regex in python
Replace $$ or more with single spaceusing Regex in python

Time:11-02

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']

CodePudding user response:

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.

CodePudding user response:

Is this what you need?:

import re
for d in data:
    d = re.sub(r'\${2,}', ' ', d)
  • Related