Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式-如何在字符串中的非字母字符和字母字符之间创建空白_Python_Regex - Fatal编程技术网

Python 正则表达式-如何在字符串中的非字母字符和字母字符之间创建空白

Python 正则表达式-如何在字符串中的非字母字符和字母字符之间创建空白,python,regex,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" 你能告诉我如何写一个常规的表达式来完成这个任务吗?提前感谢。试试这个:

我想规范化文本字符串;出于这个原因,我想保留标点符号和非字母字符(不是为了删除表情符号),但同时在每两个字母和非字母字符之间留一个空格。例如,以下字符串:

"*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"
你能告诉我如何写一个常规的表达式来完成这个任务吗?提前感谢。

试试这个:

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()
试试这个:

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()

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

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

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

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

请注意,这也会在不需要的地方添加空格。就像在空格处一样,在刺的开始/结束。很好,我更新了我的答案来纠正这个问题。你的答案更清晰。请注意,这也会在不需要的地方添加空格。就像在空格处一样,在刺的开始/结束。很好,我更新了我的答案来纠正这个问题。您的答案更清晰。@user823743,更新了答案。你必须引用这句话。谢谢你的回答@用户823743,更新了答案。你必须引用这句话。谢谢你的回答!