Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Space inside Quotes

Tags:

python

regex

I'm trying to remove white spaces before and after a phrase which is placed inside double quotation marks. Whatever I've found on google removes the spaces alright but removes the spaces before and after the quotation marks too.

txt = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."

# output:
"election laws\"are outmoded or inadequate and often ambiguous\"and should be changed."

This is the code:

import re

regex = r"(?<=[\"]) +| +(?=[\"])"

test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."

subst = ""

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

The expected output is:

"election laws \"are outmoded or inadequate and often ambiguous\" and should be changed."

Please help.

like image 293
Ron Avatar asked Jan 27 '23 03:01

Ron


1 Answers

The modified version of your code to work is:

import re

regex = '\\"\s+([^"]+)\s+\\"'

test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed \" second quotes \"."

subst = ""

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, '\"'+r'\1'+'\"' , test_str)

if result:
    print (result)

output:

election laws "are outmoded or inadequate and often ambiguous" and should be changed "second quotes".

Explanation: I replace a match of \" + spaces + (anything) + spaces + \" with \"+(anything)+\" where the () means capture group. So I can reference this capture group using the syntax r'\1'

like image 184
Pedro Borges Avatar answered Feb 07 '23 22:02

Pedro Borges