-2

I'm trying to match, last letter in string 'onlin' as any and then replace it if it matches with word offline. No luck. Please give advice, cheers.

import mitmproxy
import re

def response(flow):
    old = b'Onlin\w{1}'
    new = b'Offline'
    flow.response.content = flow.response.content.replace(old, new)

2 Answers2

5

I guess you are using the wrong function for replacement. Try re.sub.

def response(flow):
    old = b'Onlin\w'
    new = b'Offline'
    # https://docs.python.org/3/library/re.html#re.sub
    flow.response.content = re.sub(old, new, flow.response.content)
Mišo
  • 2,327
  • 1
  • 23
  • 25
2

str.replace() does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub().

The pattern Onlin. matches any string that starts with Onlin and ends with any character.

import re

old = re.compile('Onlin.')

def response(flow):
    new = 'Offline'
    flow.response.content = old.sub(new, flow.response.content)

Example:

>>> old = re.compile("Onlin.")
>>> old.sub(new, "Onlin Onlina Online")
'offlineoffline offline'
Peter
  • 628
  • 7
  • 12