Jack Kelly Jack Kelly - 1 year ago 76
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}]/, "")

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 Source
string = "jack. o'reilly? mike??!?"
puts string.gsub(/[\p{P}&&[^']]/, '')
# => jack o'reilly mike


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".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download