[英]Regex - Remove space between two punctuation marks but not between punctuation mark and letter
我有以下正则表达式来删除标点符号之间的空格。
re.sub(r'\s*(\W)\s*', r'\1', s)
在我几乎所有的测试用例中都可以正常工作,除了这个:
This is! ? a test! ?
为此我需要
This is!? a test!?
并得到
This is!?a test!?
我如何不删除它们之间的空格?
和'一个'? 我错过了什么?
这应该有效:
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
尝试这个:
string = "This is! ? a test! ?"
string = re.sub(r"(\W)\s*(\W)", r"\1\2", string)
print(string)
输出:
This is!? a test!?
为了将标点字符与 Python 中的正则表达式匹配,您可以使用(?:[^\\w\\s]|_)
模式,它匹配除字母、数字或空格之外的任何字符。
因此,您需要匹配一个或多个紧跟在标点字符 ( (?<=[^\\w\\s]|_)
) 之前的空格 ( \\s+
) 并紧跟在这样的字符 ( (?=[^\\w\\s]|_)
):
(?<=[^\w\s]|_)\s+(?=[^\w\s]|_)
请参阅在线正则表达式演示。
import re
text = "This is! ? a test! ?"
print( re.sub(r"(?<=[^\w\s]|_)\s+(?=[^\w\s]|_)", "", text) )
# => This is!? a test!?
另一种选择是利用PyPi 正则表达式模块use \\p{Punct}
inside positive lookarounds 来匹配标点符号。
例如
import regex
pattern = r"(?<=\p{Punct})\s+(?=\p{Punct})"
s = 'This is! ? a test! ?'
print(regex.sub(pattern, '', s))
输出
This is!? a test!?
请注意, \\s
也可以匹配换行符。 您还可以使用[^\\S\\r\\n]
匹配除换行符之外的空白字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.