繁体   English   中英

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

[英]RegEx- How to make a blank space between a non-alphabetic char and an alphabetic char in a string

我想规范化文本字符串; 出于这个原因,我想保留标点符号和非字母字符(不用于处理图释),但同时在每两个字母和非字母字符之间留一个空格。 例如以下字符串:

"*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"

您能告诉我如何编写常规表达式吗? 提前致谢。

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

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

与空间

例如:

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM