【发布时间】:2019-09-27 12:13:49
【问题描述】:
我有如下字符串:
s1 = 'Hello , this is a [ test ] string with ( parenthesis ) .'
我正在尝试删除标点周围的空格,因此它应该如下所示:
s1 = 'Hello, this is a [test] string with (parenthesis).'
我从这里找到了一些代码:How to strip whitespace from before but not after punctuation in python
req = re.sub(r'\s([?,.!"](?:\s|$))', r'\1', text)
我在正则表达式中添加了 ] 和 ) 以包括删除 ] 或 ) 之后的空格
req = re.sub(r'\s([?,.!\])"](?:\s|$))', r'\1', text)
所以它现在看起来像这样:
s1 = 'Hello, this is a [ test] string with ( parenthesis).'
现在我一直在尝试调整它以删除 [ 或 ( 之前的空格,但我不知道如何。当涉及到正则表达式时我很困惑。
我知道 re.sub() 正在用第一个参数替换第二个参数 (r'\1'),但我不明白 (r'\1') 的实际含义。
任何帮助将不胜感激,
干杯
【问题讨论】:
-
\1表示第一个捕获匹配组。组是模式中括号包围的内容(在您的模式([?,.!\])中)您可以通过执行(?:)(在您的模式(?:\s|$)))中拥有非捕获组 -
re.sub(r'([[(])\s+|\s+([])])(?:\s+(?=[^\w\s]))?', r'\1\2', text)(demo)?