Reputation: 14746
How do I remove leading and trailing quotes from a string only if both are present? For example
"hello world" => hello world
"hello world => "hello world
hello world" => hello world"
I tried it with gsub
, but the following removes every leading or trailing quotes, regardless if the other is present
'"hello world"'.gsub(/\A"|"\Z/, '')
# => this is ok it returns 'hello world'
'hello world"'.gsub(/\A"|"\Z/, '')
# => returns 'hello world' but should return 'hello world"'
Upvotes: 3
Views: 2552
Reputation: 13921
Nice thing with ruby is that you can write code that reads like English in many cases. The good thing about it is that it is easy to understand.
x = '"hello world"'
quote = '"'
if x.start_with?(quote) && x.end_with?(quote)
x = x[1...-1]
end
puts x #=> hello world
Upvotes: 2
Reputation: 160631
I wouldn't bother using a regex:
def strip_end_quotes(str)
str[0] == '"' && str[-1] == '"' \
? str[1..-2] \
: str
end
strip_end_quotes '"both"' # => "both"
strip_end_quotes '"left' # => "\"left"
strip_end_quotes 'right"' # => "right\""
Doing this in a single regex results in a pattern that isn't overly clear and clarity and readability is very important when coding. Being merciful to those who have to maintain the code in the future is good.
Upvotes: 1
Reputation: 168269
I think this would be more efficient than using a regex.
'"hello world'
.dup.tap{|s| s[0] = s[-1] = "" if s[0] == '"' and s[-1] == '"'}
# => "\"hello world"
'"hello world"'
.dup.tap{|s| s[0] = s[-1] = "" if s[0] == '"' and s[-1] == '"'}
# => "hello world"
'hello world"'
.dup.tap{|s| s[0] = s[-1] = "" if s[0] == '"' and s[-1] == '"'}
# => "hello world\""
Upvotes: 2
Reputation: 627536
You can use
str.gsub(/\A"+(.*?)"+\Z/m, '\1')
The pattern will match a string starting with one or more "
, then it can have any characters, any amount of them and then one or more double quotes at the end of the string. The whole string without the leading and trailing quotes will be inserted into the replacement result with the \1
backreference.
See IDEONE demo
To only trim out the first and last double qoute, you may use
str.gsub(/\A"(.*)"\Z/m, '\1')
Upvotes: 3