Search code examples
pythonregexpython-re

Regex to replace between second occurance of symbol A and symbol B


I have an example string to match:

s = 'https://john:ABCDE@api.example.com'

I am trying to replace the string ABCDE between the 2nd colon and the first occurrance of @. So my desired output is:

s_out = 'https://john:REPLACED@api.example.com'

My current code is:

import re
s_out = re.sub(r":*(.+)@api.example.com", 'REPLACED', s)

But i am unable to replace this currently.


Solution

  • You can start the match with the colon, and then prevent matching either : or @ using a negated character class

    Capture in a group starting from the @ sign, which you can then use in the replacement.

    :[^\s:@]*(@api\.example\.com)
    

    And replace with

    :REPLACED\1
    

    See a regex101 demo.

    Example

    import re
    
    s = 'https://john:ABCDE@api.example.com'
    pattern = r":[^\s:@]*(@api\.example\.com)"
    s_out = re.sub(pattern, r":REPLACED\1", s)
    print(s_out)
    

    Output

    https://john:REPLACED@api.example.com