Python 当与任意方向的正则表达式匹配时,分隔某些字符

Python 当与任意方向的正则表达式匹配时,分隔某些字符,python,regex,Python,Regex,我有这样的想法: text = "hey;)there" 需要这个: text = "hey ;) there" 我做了两次传球: 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) 我相信一定有一种有效的方法。你可以交替使用lookaheads和lookbehinds >>> re.sub('(?

我有这样的想法:

text = "hey;)there"
需要这个:

text = "hey ;) there"
我做了两次传球:

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)

我相信一定有一种有效的方法。你可以交替使用lookaheads和lookbehinds

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

>>>re.sub('(?结果不一样:)缺少两个字符。我只想分离模式。请注意,如果使用三重引号的
r''“原始字符串”,则可以内联包含解释
re.VERBOSE
标志,通常用于保存代码中的信息。@Kevad缺少哪些字符?我需要“嘿;)在那里”,上面的代码片段给出了“he;)此处'@Kevad,如您所愿..您可以使用
\W{2}
作为非单词字符..请随意投票..:)您能更明确地说明您要处理和不想处理的情况吗?这里的实际任务是什么?只想分离一些与“\w”不匹配的字符,比如表情符号在这种情况下,
r'(\w{2,})
会这样做吗?然后你可以用
r'\1'
-@jornsharpe给我这个“hi\x01那里”:)注意正则表达式应该是
{2}
表示“正好两个”,或者
{2,}
表示“至少两个”<代码>:
-
都由
\W
匹配。
(?<=[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