![](/img/trans.png)
[英]Python: How to remove empty quotes and a new line from the beginning of the string?
[英]remove empty quotes from string using regex
我想刪除標點符號,例如“”,“”, 、、
, "", '' from my string using regex. The code so far I've written only removes the ones which space between them. How do I remove the empty ones such as '',
, "", '' from my string using regex. The code so far I've written only removes the ones which space between them. How do I remove the empty ones such as '',
#Code
s = "hey how ' ' is the ` ` what are '' you doing `` how is everything"
s = re.sub("' '|` `|" "|""|''|``","",s)
print(s)
我的預期結果:
hey how is the what are you doing how is everything
您可以使用此正則表達式來匹配所有此類引號:
r'([\'"`])\s*\1\s*'
碼:
>>> s = "hey how ' ' is the ` ` what are '' you doing `` how is everything"
>>> print (re.sub(r'([\'"`])\s*\1\s*', '', s))
hey how is the what are you doing how is everything
正則表達式詳細信息:
([\\'"`])
:匹配給定的引號之一並將其捕獲在組#1中 \\s*
:匹配0個或多個空格 \\1
:使用第1組的反向引用確保我們匹配相同的結束語 \\s*
:匹配0個或多個空格 在這種情況下,為什么不匹配所有單詞字符,然后再將它們組合起來?
' '.join(re.findall('\w+',s))
# 'hey how is the what are you doing how is everything'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.