Reputation: 5071
The string is the following:
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
I would like the comma inside this substring "$1,455.85"
to be removed but not the other commas.
I tried this but failed:
import re
pattern = r'$\d(,)'
re.sub(pattern, '', s)
Why doesn't this work?
Upvotes: 1
Views: 52
Reputation: 1
import re
pattern = r"(\$\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
print(s)
s = re.sub(pattern, r'\1', s)
print(s)
Output:
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%
But it doesn't work for "$1,455,789.85"
Upvotes: 0
Reputation: 1979
You need a positive lookbehind assertion, i.e., match a comma if it is preceded by a $
(note that $
needs to be escaped as \$
) followed by a digit (\d
). Try:
>>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
>>> pattern = r'(?<=\$\d),'
>>> re.sub(pattern, '', s)
'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%'
Upvotes: 2