1

I want to remove punctuation 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)

My expected outcome:

hey how is the what are you doing how is everything
5
  • Whats your expected output? Commented Sep 24, 2018 at 20:57
  • Just mentioned. Commented Sep 24, 2018 at 20:58
  • use ? after the space to match on it, optionally. re.sub("' ?'|` ?`|" ?""',"",s) Commented Sep 24, 2018 at 20:58
  • Why use regex? You can create a new string, loop through your original string and add characters to your new string if they are not punctuation: newstr = "" for char in mystr: if char not in ('"', ... (put punctuation characters here)): newstr += char Commented Sep 24, 2018 at 21:02
  • You want to remove paired quotes with/without whitespace in between ? You can't just match stuff like "" without matching all quotes. Commented Sep 24, 2018 at 21:59

2 Answers 2

4

You may use this regex to match all such quotes:

r'([\'"`])\s*\1\s*'

Code:

>>> 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 Details:

  • ([\'"`]): Match one of the given quotes and capture it in group #1
  • \s*: Match 0 or more whitespaces
  • \1: Using back-reference of group #1 make sure we match same closing quote
  • \s*: Match 0 or more whitespaces

RegEx Demo

Sign up to request clarification or add additional context in comments.

Comments

1

In this case, why not match all word characters, and then join them?

' '.join(re.findall('\w+',s))
# 'hey how is the what are you doing how is everything'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.