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?

7
  • You're not using regular expressions at all, this is just plain string replacement. Commented Aug 9, 2021 at 12:00
  • You are looking for re.sub Commented Aug 9, 2021 at 12:01
  • (also note that $ has special meaning in regular expressions and presumably you need to escape it) Commented Aug 9, 2021 at 12:02
  • @mkrieger1 yes.. I even tried to escape the character but same result Commented Aug 9, 2021 at 12:05
  • 1
    Yes of course, see earlier comments. This is another, better, duplicate: stackoverflow.com/questions/16720541/… Commented Aug 9, 2021 at 12:06

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.