victorbrowser
victorbrowser

Reputation: 71

Rearrange strings with regex from file

So I have a file with strings that have a delimiter (::) I want to switch them around using regex but my attempts do not work

File contents:

foo:bar
foo:bar
foo:bar

My code:

combo = open("combo.txt", 'r')
outfile = open("checked.txt", 'w')
outfile.write(re.sub(r'(\d+)-(\d+)', r'\2-\1', combo.readlines()))
outfile.close

Expected output:

bar:foo
bar:foo
bar:foo

Upvotes: 2

Views: 130

Answers (4)

Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9447

Try with this regex: (\w+):(\w+) and replace with \2:\1

Code:

combo = open("combo.txt", 'r')
outfile = open("checked.txt", 'w')
outfile.write(re.sub(r'(\w+):(\w+)', r'\2:\1', combo.readlines()))
outfile.close

Demo here

Upvotes: 1

Tomalak
Tomalak

Reputation: 338326

Avoid regex when there is no need for them.

This task is "split - reverse - join".

with open("combo.txt", 'r') as combo, open("checked.txt", 'w') as outfile:
    outfile.write(':'.join(reversed(line.split(':', 2))) for line in combo)

Upvotes: 2

Shubham Sharma
Shubham Sharma

Reputation: 71687

You can simply use string.split method to get the desired result, there is no need to use regex. Use:

with open("combo.txt") as r, open("checked.txt", "w") as w:
    for line in r:
        tokens = line.strip().split(":")
        w.write(f"{tokens[1]}:{tokens[0]}\n")

If you want to use regex,

import re

with open("combo.txt") as r, open("checked.txt", "w") as w:
    for line in r:
        w.write(re.sub(r"(\w+):(\w+)", r"\g<2>:\g<1>\n", line.strip()))

After executing the above code, the contents of checked file should look like:

bar:foo
bar:foo
bar:foo

Upvotes: 0

goosfraba
goosfraba

Reputation: 80

Basically you need to do what was already suggested but I would loosen a bit the regex to also match on numbers and other characters until it finds the first :. Check here: https://regex101.com/r/kH6kHn/1

Upvotes: 0

Related Questions