繁体   English   中英

使用正则表达式从字符串中删除空引号

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM