How to delete specific characters from a string in Ruby?

前端 未结 5 1821
失恋的感觉
失恋的感觉 2021-02-01 00:04

I have several strings that look like this:

\"((String1))\"

They are all different lengths. How could I remove the parentheses from all these s

相关标签:
5条回答
  • 2021-02-01 00:33

    Do as below using String#tr :

     "((String1))".tr('()', '')
     # => "String1"
    
    0 讨论(0)
  • 2021-02-01 00:42

    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"
    
    0 讨论(0)
  • 2021-02-01 00:43

    Using String#gsub with regular expression:

    "((String1))".gsub(/^\(+|\)+$/, '')
    # => "String1"
    "(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
    # => " parentheses "
    

    This will remove surrounding parentheses only.

    "(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
    # => " This (is) string "
    
    0 讨论(0)
  • 2021-02-01 00:58

    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.

    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
    
    0 讨论(0)
  • 2021-02-01 00:58

    Here is an even shorter way of achieving this:

    1) using 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"
    
    0 讨论(0)
提交回复
热议问题