adding space before and after a comma and dash in python using regex

Viewed 208

I've already looked at so many topics on this and maybe I am not understanding something, but in a phrase like this:

"hello-goodbye C-GOOD" or "100.89 D-FARM" I want to add a space before and after characters like ".,-" but I don't want those spaces in C-GOOD or D-FARM"

This is the final result I want: "hello - goodbye C-GOOD" "100 . 89 D-FARM" but no matter what I try I either get spaces on everything or no spaces on any of the dashes:

I either get: "hello - goodbye C - GOOD" "100 . 89 D - FARM" or "hello-goodbye C-GOOD" "100 . 89 D-FARM" Here is what I have tried:

text= re.sub(r'([.,!?()-]+)^(?<!C)', r' \1 ', text)
text= re.sub(r'([.,!?()-]+)^(?<!C-)', r' \1 ', text)
text= re.sub(r'([.,!?()-]+)(?<!C-GOOD)', r' \1 ', text)
text= re.sub(r'([.,!?()-]+)(?!C-GOOD)', r' \1 ', text)

If anyone can help or knows what I am doing wrong that would be wonderful. Thank-you.

2 Answers

We can use re.sub here with a callback function, which will exclude C-GOOD and D-FARM from being replaced:

inp = ["hello-goodbye C-GOOD", "100.89 D-FARM"]
def repl(m):
    if m.group() == "C-GOOD" or m.group() == "D-FARM":
        return m.group()
    else:
        return " - "
output = [re.sub(r'C-GOOD|D-FARM|[.,-]', repl, x) for x in inp]
print(output)  # ['hello - goodbye C-GOOD', '100 - 89 D-FARM']

The trick here is in the regex pattern C-GOOD|D-FARM|[.,-], which will attempt to match C-GOOD or D-FARM before attempting to also match a comma, dot, or dash. re.sub then passes this match to a callback function, which only adds space in the case of the [.,-] separator.

Mismatches .,- join uppercase letters.

import re

s = "hello-goodbye C-GOOD 100.89 D-FARM"

print(re.sub("(?<![A-Z])([.,-])(?![A-Z]+)", r" \g<1> ", s))
# hello - goodbye C-GOOD 100 . 89 D-FARM
Related