gpt4 book ai didi

python - 正则表达式 - 删除两个标点符号之间的空格,但不删除标点符号和字母之间的空格

转载 作者:行者123 更新时间:2023-12-02 00:05:03 26 4
gpt4 key购买 nike

我有以下用于删除标点符号之间空格的正则表达式。

re.sub(r'\s*(\W)\s*', r'\1', s)

它在我几乎所有的测试用例中都运行良好,除了这个:

This is! ? a test! ?

我需要的

This is!? a test!?

得到

This is!?a test!?

如何不删除 ? 和“a”之间的空格?我错过了什么?

最佳答案

这应该有效:

import re

str = 'This is! ? a test! ?'
res = re.sub(r'(?<=[?!])\s+(?=[?!])', '', str)
print(res)

输出:

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

关于python - 正则表达式 - 删除两个标点符号之间的空格,但不删除标点符号和字母之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60902470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com