[英]Regex for removing whitespace after a parenthesis python
我有如下字符串:
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') 的實際含義。
任何幫助,將不勝感激,
干杯
這可能有助於使用lookbehind & lookahead。
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))
Output:
Hello, this is a [test] string with (parenthesis).
一種方法是不在括號內的開頭和結尾處捕獲空格,即
(parens start) some space (capture text) some space (parens close)
| | |
Group 1 Group 2 Group 3
匹配. or, preceded by space using alternation
. or, preceded by space using alternation
並將其捕獲在單獨的組中
([[({])\s*(.*?)\s*([\]\)\}])|\s+([,.])
替換為\1\2\3\4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.