使用正则表达式在 python 中的逗号和破折号前后添加 space

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

我已经看了很多关于这个的话题,也许我不明白什么,但是用这样的短语:

“hello-goodbye C-GOOD”或“100.89 D-FARM” 我想在“.,-”之类的字符前后添加 space,但我不希望 C-GOOD 中的那些 space 或 D-FARM

这是我想要的最终结果: “你好 - 再见 C-GOOD” “100 . 89 D-FARM” 但无论我尝试什么,我要么在所有内容上都得到 spaces,要么在任何破折号上都没有 spaces:

我得到:“你好 - 再见 C - 好”“100 . 89 D - FARM”或 “你好再见 C-GOOD” “100 . 89 D-FARM” 这是我尝试过的:

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

如果有人能提供帮助或知道我做错了什么,那就太好了。谢谢。

我们可以在这里使用 re.sub 和回调函数,这将排除 C-GOODD-FARM 被替换:

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']

这里的技巧在于正则表达式模式 C-GOOD|D-FARM|[.,-],它将尝试匹配 C-GOODD-FARM ,然后再尝试匹配 逗号、点或破折号。 re.sub 然后将此匹配传递给回调函数,该函数仅在 [.,-] 分隔符的情况下添加 space。

不匹配 .,- 连接大写字母。

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