我想在两个分隔符之间替换/复制一个子字符串——例如:
"This is (the string) I want to replace"
我想去掉字符(
和之间的所有内容)
,并将 substr 设置为一个变量——是否有内置函数来执行此操作?
我想在两个分隔符之间替换/复制一个子字符串——例如:
"This is (the string) I want to replace"
我想去掉字符(
和之间的所有内容)
,并将 substr 设置为一个变量——是否有内置函数来执行此操作?
var = "This is (the string) I want to replace"[/(?<=\()[^)]*(?=\))/]
var # => "the string"
我会这样做:
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"
str = "This is (the string) I want to replace"
str.match(/\((.*)\)/)
some_var = $1 # => "the string"
据我了解,您想要删除或替换子字符串以及设置一个等于该子字符串的变量(不带括号)。有很多方法可以做到这一点,其中一些是其他答案的轻微变体。这是另一种方式,它也允许括号内有多个子字符串,从@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", ""]
在正则表达式中,?
in.*?
使.*
“懒惰”。 gsub
将每个匹配传递m
给块;该块剥离括号并将其添加到vars
,然后返回替换字符串。此正则表达式也适用:
/\([^\(]*\)/