Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove unwanted spaces between quotations

Is there a more elegant way to remove spaces between quotations (despite using code like this:

input = input.replace('" 12 "', '"12"')`)

from a sentence like this:

 At " 12 " hours " 35 " minutes my friend called me.

Thing is that numbers can change, and then the code won't work correctly. :)

like image 683
Stimy Avatar asked Dec 18 '22 11:12

Stimy


1 Answers

You can use regular expressions as long as your quotations are reasonably sane:

re.sub(r'"\s*([^"]*?)\s*"', r'"\1"', input)

The pattern reads as "quote, any number of spaces, stuff that's not a quote (captured), followed by any number of spaces and a quote. The replacement is just the thing you captured in quotes.

Notice that the quantifier in the capture group is reluctant. That ensures that you don't capture the trailing spaces.

like image 152
Mad Physicist Avatar answered Dec 26 '22 13:12

Mad Physicist