codescribble
codescribble

Reputation: 67

Ruby Regex to keep single apostrophe but remove end apostrophes

For the following string, how can I get rid of the enclosing single quotes?

string: "'won't'"
desired result: "won't" 

looking for a regex expression that I can use in gsub to replace '' with empty string. e.g.

arr = ["'don't'", "stop", "str%&eaming"]
arr.map { |letter| gsub(/pattern/, ""}

should return

=> ["don't", "stop", "streaming"]

Upvotes: 0

Views: 773

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Keep it simple.

def strip_single_quotes(str)
  str[0]=="'" && str[-1]=="'" ? str[1..-2] : str
end

arr = ["'don't'", "stop", "str%&eaming", "'twas", "''twas'", "'fishin''", "she'd've"]

arr.each { |word| puts "#{word.ljust(12)} -> #{strip_single_quotes(word) }" }
'don't'      -> don't
stop         -> stop
str%&eaming  -> str%&eaming
'twas        -> 'twas
''twas'      -> 'twas
'fishin''    -> fishin'
she'd've     -> she'd've

You could instead write the body of strip_single_quotes as follows.

str =~ /\A'.*'\z/ ? str[1..-2] : str

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26444

This worked for me in irb

arr.map { |l| l.gsub(/^'|'$|%&/, '') }

Note that this will not modify the original way. To destructively mutate the array, you will need to use a bang method, in this case arr.map!.

Here is a simple explanation.

In the regex, we are searching for matches that either start or end with an apostrophe, or that contain the two special characters in the third item.

The symbol ^ is used to indicate the line begins with a certain substring. On the other hand, the symbol $ is used to indicate a line ending with a certain substring. The | operator is common in Computer Science to represent an or conditional.

However, if you have a string that spans multiple lines, you should consider using the \A and \z expressions to indicate the start and end of a string.

My output in irb is as follows

=> ["don't", "stop", "streaming"]

Upvotes: 1

Related Questions