我有这样的事情:
text = "hey;)there"
需要这个:
text = "hey ;) there"
我正在做2次传球:
op_1 = re.sub(r'([a-zA-Z])([:;()])', r'\1 \2', text)
final_result = re.sub(r'([:;()])([a-zA-Z])', r'\1 \2', op_1)
我相信必须有一个有效的方法。
答案 0 :(得分: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