Jack Kelly Jack Kelly - 1 month ago 6
Ruby Question

I want to match all punctuation in my regexp except apostrophes. How do i do that in Ruby?

This is my code so far:

def alternate_words(string)
string.gsub(/[\p{P}]/, "")
end


I am looking for a way to add exceptions to my regular expressions. Is it possible or do I have to list them all out?

Answer
string = "jack. o'reilly? mike??!?"
puts string.gsub(/[\p{P}&&[^']]/, '')
# => jack o'reilly mike

Docs:

A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]] describes the same set as [a-z0-9]. However, character classes also support the && operator which performs set intersection on its arguments.

So, [\p{P}&&[^']] is "any character that is punctuation and also not an apostrophe".