我有以下正则表达式用于删除标点符号之间的空格。
re.sub(r'\s*(\W)\s*', r'\1', s)
它在我的几乎所有测试用例中都运行良好,除了这个:
This is! ? a test! ?
为此我需要有
This is!? a test!?
and get
This is!?a test!?
我如何不删除它们之间的空间?
和“一个”?我缺少什么?
这应该有效:
import re
str = 'This is! ? a test! ?'
res = re.sub(r'(?<=[?!])\s+(?=[?!])', '', str)
print(res)
Output:
This is!? a test!?
解释:
(?<=[?!]) # positive lookbehind, make sure we have a punctuation before (you can add all punctuations you want to check)
\s+ # 1 or more spaces
(?=[?!]) # positive lookahead, make sure we have a punctuation after
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)