I want to strip leading and trailing quotes, in Ruby, from a string. The quote character will occur 0 or 1 time. For example, all of the following should be converted to foo,bar:
"foo,bar"
"foo,bar
foo,bar"
foo,bar
To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.
In double quoted strings you would have to escape the backslash symbol to accomplish the same result. Examples of other escape sequences that work the same way are: \t , \s and \b , which represent a tab, a space and a backspace respectively.
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
The basic difference between these two methods is Single quotes can not hold/print escape sequences directly, while double quotes can. i.e. Double quoted strings are used for String Interpolation in Ruby.
I can use gsub to search for the leading or trailing quote and replace it with an empty string:
s = "\"foo,bar\"" s.gsub!(/^\"|\"?$/, '')
As suggested by comments below, a better solution is:
s.gsub!(/\A"|"\Z/, '')
You could also use the chomp
function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:
'"foo,bar"'.rchomp('"').chomp('"')
Implementing rchomp
is straightforward:
class String def rchomp(sep = $/) self.start_with?(sep) ? self[sep.size..-1] : self end end
Note that you could also do it inline, with the slightly less efficient version:
'"foo,bar"'.chomp('"').reverse.chomp('"').reverse
EDIT: Since Ruby 2.5, rchomp(x)
is available under the name delete_prefix
, and chomp(x)
is available as delete_suffix
, meaning that you can use
'"foo,bar"'.delete_prefix('"').delete_suffix('"')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With