0

How to use python to replace 'http://xyz.example.com' to 'http://example.com' with regular expression

Note: 'xyz' is just a template. it may be '123' or 'abc-123'

dorayo
  • 47
  • 6

1 Answers1

3

This would do it:

import re

input = 'http://xyz.example.com'

output = re.sub(r'(?<=http:\/\/).*?\.', '', input)

print(output)

Regex demo
Python demo

  1. (?<=http:\/\/) is a positive look behind for http://
  2. .*?\. matches everything that isn't a new line token lazily up until the first .
Olian04
  • 6,480
  • 2
  • 27
  • 54