1

Say I have a string:

'hello$ world$ $'

How do I remove only the second occurrence of the $

Or if I have str'ing'h

How do I use re.sub() to only remove the second apostrophe? Without writing a big long function that breaks it into each character finds the index of all the apostrophes etc.

Itamar Mushkin
  • 2,420
  • 2
  • 12
  • 27
Jamalan
  • 161
  • 7
  • if you show your attempt then you will get better answers. – anubhava Feb 24 '20 at 06:05
  • I have tried, what's felt like everything. I spent 1.5 full hours on a test trying to come up with an answer and could not. Believe me, I know this is not the best formatted question. But can someone please answer the question? – Jamalan Feb 24 '20 at 06:05

1 Answers1

0

You may use this regex:

>>> import re
>>> s = 'hello$ world$ $'
>>> print ( re.sub(r'^([^$]*\$[^$]*)\$', r'\1:', s) )
hello$ world: $

RegEx Details:

  • ^: Start
  • (: Start capture group #1
    • [^$]*: Match 0 or more characters that are not $
    • \$: Match a $
    • [^$]*: Match 0 or more characters that are not $
  • ): End capture group #1
  • \$: Match a $

Use this for second problem is replacing second single quote:

s = re.sub(r"^([^']*'[^']*)'", r'\1:', s)
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • This works perfectly, can I ask why is the portion of the pattern outside the capture group the one that gets replaced and not the capture group?... – Jamalan Feb 24 '20 at 06:26
  • Part outside capture group is what you're replacing so that must be outside the capture group. – anubhava Feb 24 '20 at 06:33