RegEx-如何在非字母字符和字符串中的字母字符之间创建空格

时间:2013-03-13 20:04:31

标签: python regex

我想规范化文本字符串;因此我想保留标点符号和非字母字符(不是要检测表情符号),但同时在每两个字母和非字母字符之间留一个空格。例如,以下字符串:

"*I love u*"
"Hi, life is great:)hehe"
"I will go uni.cul"

应转换为:

"* I love u *"
"Hi , life is great :) hehe"
"I will go to uni . cul"

你能告诉我如何写一个正常的表达来做这件事吗?提前谢谢。

2 个答案:

答案 0 :(得分:4)

您可以替换此表达式的匹配项:

(?<=[^\w\s])(?=\w)|(?<=\w)(?=[^\w\s])

空格

例如:

re.sub(r'(?<=[^\w\s])(?=\w)|(?<=\w)(?=[^\w\s])', ' ', str)

答案 1 :(得分:2)

试试这个:

x = '''*I love u*
    Hi, life is great:)hehe
    I will go uni.cul'''

def rep(matchobj):
    return ' ' + matchobj.group(0) + ' '

print re.sub('[^a-zA-Z0-9\s]+', rep, x).strip()