我有几个看起来像这样的字符串:
"((String1))"
它们的长度都不同。我如何在循环中删除所有这些字符串中的括号?
使用String#tr
方法按照下面的方式执行:
"((String1))".tr('()', '')
# => "String1"
tr!
函数可以原地修改字符串,例如 my_string.tr!(')(','')
。 - bonh对于那些查找性能的人,看起来#delete
和#tr
速度大约相同,并且比gsub
快2-4倍。
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
使用正则表达式与String#gsub
方法:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
这将仅移除周围的括号。
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
irb(main)> "((String1))"[/[^()]+/]
=> "String1"
^
- 匹配不在字符类中的任何内容。在字符类内部,我们有 (
和 )
或者使用全局替换 "AKA: gsub",就像其他人已经提到的那样。
irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"
((a))b
上有不同的结果。第一个只会返回 a
,而第二个将返回 ab
。 - Ulysse BN
def chop_chop(s) chop_one_way(chop_one_way(s,')').reverse,'(').reverse end
和def chop_one_way(s,c); s.chop! while s[-1] == c; s; end chop_chop "(((abc)))" # => "abc"
。 - Cary Swoveland