我有如下字符串:
s1 = 'Hello , this is a [ test ] string with ( parenthesis ) .'
我正在尝试删除标点符号周围的空白,因此它应如下所示:
s1 = 'Hello, this is a [test] string with (parenthesis).'
我从这里找到了一些代码:如何在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')的实际含义。
任何帮助,将不胜感激,
干杯
这可能有助于使用后向和前向。
import re
s1 = 'Hello , this is a [ test ] string with ( parenthesis ).'
#print(re.sub(r"(?<=\[|\()(.*?)(?=\)|\])", lambda x: x.group().strip(), s1))
print(re.sub(r'(\s([?,.!"]))|(?<=\[|\()(.*?)(?=\)|\])', lambda x: x.group().strip(), s1))
输出:
Hello, this is a [test] string with (parenthesis).
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句