从任一方向正则表达式 python 匹配时分隔某些字符

separate certain characters when matched from either direction regex python

我有这样的东西:

text = "hey;)there"

需要这个:

text = "hey ;) there"

我正在做 2 遍:

op_1 = re.sub(r'([a-zA-Z])([:;()])', r' ', text)
final_result = re.sub(r'([:;()])([a-zA-Z])', r' ', op_1)

我相信一定有一个有效的方法。

您可以交替使用先行和后行

>>> re.sub('(?<=[a-zA-Z])(?=[:;()])|(?<=[:;()])(?=[a-zA-Z])', ' ', text)
'hey ;) there'

正则表达式分解

(?<=[a-zA-Z]) #Lookbehind to match an alphabet
(?=[:;()]) #Lookahead to match the position of signs
| Alternation(OR)
(?<=[:;()]) #Lookbehind to match the position of signs
(?=[a-zA-Z]) #Lookahead to match an alphabet