-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)
4
  • Does it work if you remove that character in Onlin\w{1}’? Commented May 26, 2018 at 13:13
  • It got in there by accident, doesn't help. Commented May 26, 2018 at 13:16
  • It's not clear what you're asking. Can you explain what the expected output is? Commented May 26, 2018 at 13:16
  • In flow.response.content.replace value of variable 'old' is replace by value of the variable 'new'. Im trying to use regex to match value of variable old with the last character as wildcard. But it doesn't work. Basically 'onlin' + [a-z, 0-9] Commented May 26, 2018 at 13:20

2 Answers 2

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

1 Comment

Works very well, cheers, I'm quite new to this
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'

1 Comment

This did not work, but thank You for your time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.