Я хочу удалить знаки препинания, такие как "", "", ,
, "", '' from my string using regex. The code so far I've written only removes the ones which space between them. How do я 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 я 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
RegEx Подробности:
([\'"'])
: Сопоставьте одну из заданных цитат и возьмите ее в группу # 1\s*
: совпадение 0 или более пробелов\1
: Используя обратную ссылку группы # 1, убедитесь, что мы сопоставляем ту же цитату закрытия\s*
: совпадение 0 или более пробеловВ этом случае, почему не совпадают все слова, а затем присоединяются к ним?
' '.join(re.findall('\w+',s))
# 'hey how is the what are you doing how is everything'