0

I am trying to match and replace multiple characters in a string.

str1 = 'US$0.18'
reg = 'AUS$|US$|HK$|MK$'
#reg = 'AUS\$|US\$|HK\$|MK\$' <-- doesn't work
#reg = 'US$' <-- this works
str1 = str1.replace(reg, '')

This doesn't replace US$ which I expected to.

What am I missing here?

Azima
  • 3,835
  • 15
  • 49
  • 95

1 Answers1

2

You can do that using re.sub(). Since $ has a special meaning in re, we need to escape it by appending a \ in front of it.

  • (AUS|US|HK|MK)\$ - Finds a match that has either of AUS, US, HK or MK that is followed by a $.
  • re.sub(r'(AUS|US|HK|MK)\$',r'', s) - Replaces the matched string with a '' of string s.
import re

s = "US$0.18 AUS$45 HK$96"
x = re.sub(r'(AUS|US|HK|MK)\$',r'', s)
print(x)
0.18 45 96
Ram
  • 4,724
  • 2
  • 14
  • 22