Liky
Liky

Reputation: 1247

Remove all the non words except quote in regex

I have the following:

string = re.sub("[^A-Za-z]]", ' ', string)

This works to remove all the non words. Now I would like to do almost the same but keep the single quotes in my string this time. How do I need to change my regex?

Example: Queen's son is sleeping, but he will wake up.

Result: queen's son is sleeping but he will wake up

Upvotes: 0

Views: 68

Answers (1)

SCouto
SCouto

Reputation: 7928

You can just include the single quote escaped in your group:

([^A-Za-z\'])

Including it in your example:

string = re.sub("[^A-Za-z\']", ' ', string)

Edit: You don't need to escape single quote so:

string = re.sub("[^A-Za-z']", ' ', string)

Upvotes: 1

Related Questions