你如何剥夺红宝石中的子串?

时间:2013-11-05 14:14:54

标签: ruby

我想在两个分隔符之间替换/复制子字符串 - 例如:

"This is (the string) I want to replace" 我想删除字符()之间的所有内容,并将substr设置为变量 - 是否有内置函数来执行此操作?

4 个答案:

答案 0 :(得分:3)

var = "This is (the string) I want to replace"[/(?<=\()[^)]*(?=\))/]
var # => "the string"

答案 1 :(得分:3)

我会这样做:

my_string = "This is (the string) I want to replace"

p my_string.split(/[()]/) #=> ["This is ", "the string", " I want to replace"]

p my_string.split(/[()]/)[1] #=> "the string"

以下是另外两种方法:

/\((?<inside_parenthesis>.*?)\)/ =~ my_string 
p inside_parenthesis #=> "the string"

my_new_var =  my_string[/\((.*?)\)/,1]
p my_new_var  #=> "the string"

编辑 - 解释最后一种方法的示例:

my_string = 'hello there'
capture = /h(e)(ll)o/ 

p my_string[capture]    #=> "hello"
p my_string[capture, 1] #=> "e"
p my_string[capture, 2] #=> "ll"

答案 2 :(得分:1)

str = "This is (the string) I want to replace"

str.match(/\((.*)\)/)

some_var = $1  # => "the string"

答案 3 :(得分:0)

据我所知,你想删除或替换一个子字符串,并设置一个等于该子字符串的变量(没有括号)。有很多方法可以做到这一点,其中一些是其他答案的轻微变体。这是另一种允许括号内多个子串的可能性,从@ sawa的评论中获取:

def doit(str, repl)
  vars = []
  str.gsub(/\(.*?\)/) {|m| vars << m[1..-2]; repl}, vars
end

new_str, vars = doit("This is (the string) I want to replace", '')  
new_str # => => "This is  I want to replace" 
vars    # => ["the string"] 

new_str, vars = doit("This is (the string) I (really) want (to replace)", '')  
new_str # => "This is  I  want" 
vars    # => ["the string", "really, "to replace"] 

new_str, vars = doit("This (short) string is a () keeper", "hot dang")  
new_str # => "This hot dang string is a hot dang keeper" 
vars    # => ["short", ""]

在正则表达式中,?中的.*?使.*“懒惰”。 gsub将每个匹配m传递给该区块;该块剥离了parens并将其添加到vars,然后返回替换字符串。这个正则表达式也有效:

/\([^\(]*\)/