我有几个这样的字符串:
"((String1))"
它们都是不同长度的。我怎样才能在一个循环中删除所有这些字符串中的括号呢?
Using String#gsub with regular expression:
String#gsub
"((String1))".gsub(/^\(+|\)+$/, '') # => "String1" "(((((( parentheses )))".gsub(/^\(+|\)+$/, '') # => " parentheses "
This will remove surrounding parentheses only.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '') # => " This (is) string "
Do as below using String#tr :
String#tr
"((String1))".tr('()', '') # => "String1"
If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:
s = "((String1))" s = s[2...-2] p s # => "String1"
If you want to remove all parentheses from the string you can use the delete method on the string class:
s = "((String1))" s.delete! '()' p s # => "String1"
For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.
#delete
#tr
gsub
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
Here is an even shorter way of achieving this:
1) using Negative character class pattern matching
Negative character class pattern matching
irb(main)> "((String1))"[/[^()]+/] => "String1"
^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )
^
(
)
Or with global substitution "AKA: gsub" like others have mentioned.
irb(main)> "((String1))".gsub(/[)(]/, '') => "String1"
Use String#delete:
"((String1))".delete "()" => "String1"