匹配函数的正则表达式 Ruby

Regex for match function Ruby

我正在尝试提取字符串的某些部分并将它们放入 Ruby 数组中。
我有一个像这样的字符串:

test = ["pack_1 (>=5.0.2)", "pack_2", "pack_3", "pack_4 (>=4.3.0)"]    

我想要一个与 match 一起使用的正则表达式来提取这些部分 (pack_1, pack_2, pack_3, pack_4) 然后我将把它们放入数组中。最终结果将类似于:

[pack_1, pack_2, pack_3, pack_4]

片段部分:

if line.match(/([^\s]+)/).to_s.length > 0
 array << line.match(/[^\s]+.=.\[(.*,)/).to_s // The regex here does not work proparly     
end 

我想这就是您要找的

test = "test = ['Alice (>=5.0.2)', 'John', 'Mike', 'test (>=4.3.0)']"

test.gsub(/\s\(.*?\)/, '')

调用这个方法后变量应该是这样的

"test = ['Alice', 'John', 'Mike', 'test']"

如果你想去掉 test

,只需 trim 以 slice(7..-1) 开头
"['Alice', 'John', 'Mike', 'test']"