How to delete specific characters from a string in Ruby?

前端 未结 5 1822
失恋的感觉
失恋的感觉 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: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"
    

提交回复
热议问题