Ruby 如果前导引号和尾随引号都存在,则从字符串中删除它们
如何从字符串中删除前导引号和尾随引号(仅当两者都存在时)Ruby 如果前导引号和尾随引号都存在,则从字符串中删除它们,ruby,regex,Ruby,Regex,如何从字符串中删除前导引号和尾随引号(仅当两者都存在时) "hello world" => hello world "hello world => "hello world hello world" => hello world" 我用gsub试过了,但是下面删除了每个前导引号或尾随引号,不管是否存在其他引号 '"hello world"'.gsub(/\A"|"\Z/, '') # => this is ok it returns 'hello world' 'he
"hello world" => hello world
"hello world => "hello world
hello world" => hello world"
我用gsub
试过了,但是下面删除了每个前导引号或尾随引号,不管是否存在其他引号
'"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"'
你可以用
str.gsub(/\A"+(.*?)"+\Z/m, '\1')
模式将匹配一个以一个或多个“
开头的字符串,然后它可以有任意数量的字符,然后在字符串末尾有一个或多个双引号。不带前导引号和尾随引号的整个字符串将用\1
反向引用插入替换结果
看
要仅修剪第一个和最后一个双qoute,可以使用
str.gsub(/\A"(.*)"\Z/m, '\1')
我认为这比使用正则表达式更有效
'"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\""
我不会费心使用正则表达式:
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\""
在单个正则表达式中执行此操作会导致模式不太清晰,在编码时,清晰性和可读性非常重要。对将来必须维护代码的人仁慈是件好事。ruby的好处是,在许多情况下,您可以编写类似英语的代码。好处是它很简单理解
x = '"hello world"'
quote = '"'
if x.start_with?(quote) && x.end_with?(quote)
x = x[1...-1]
end
puts x #=> hello world
如果
(.*)
贪婪,+难道不是毫无用处吗?请看:我很确定您想要懒量词..上浮,但我认为您不想要结尾处的s
修饰符。在Ruby中,s
修饰符表示正则表达式的编码是Windows-31J()。@JoshCrozier:是的,你是对的。我很忙,忘了这一点。如果我只想删除开头和结尾的“一个”,那会是什么样子?@23tux:只需删除+
s。此外,您可能需要检查字符串的最末端,并使用\z
而不是\z
。使用.gsub(/\a)(.*)\z/m,'\1')
或.gsub(/\a)()(“.*”\z/m),\1'))
(更新了答案)。我更喜欢gsub
解决方案,但由于您的观点是正确的,所以我认为这更快:虽然不是重复,但非常接近,可以给您一些想法。