Alan Alan - 2 months ago 4
Python Question

regex - swap two phrases around

Python 3. Each line is constructed of a piece of text, then a pipe symbol, then a second piece of text.
I want to swap the two pieces of text around and remove the pipe.
This is the code so far:

p = re.compile('^(.*) \| (.*)$', re.IGNORECASE)
mytext = p.sub(r'\2\1', mytext)

Yet for some reason that I can't work out, it is not matching.
A sample of the text it should be matching is (ironically):

( | [Regular Expressions 101 - YouTube]

and should end up like:

[The Field Expedient Pump Drill - YouTube](

(in other words, the code is formatting the links into the format expected of a markdown converter).

Here is the full code:

#! /usr/bin/env python3

import re, os

def create_text(myinputfile):
with open(myinputfile, 'r', encoding='utf-8') as infile:
mytext =
return mytext

def reg_replace(mytext):
p = re.compile('^(.*) \| (.*)$', re.IGNORECASE)
mytext = p.sub(r'\2\1', mytext)
return mytext

def write_out(mytext, myfinalfile):
with open(myfinalfile, 'w') as myoutfile:

def main():
mytext = create_text('')
mytext = reg_replace(mytext)
write_out(mytext, '')
os.rename("", "")
os.rename("", "")



This should help you. (View demo on regex101)


Sub with: