Home > Enterprise >  Regex for match function Ruby
Regex for match function Ruby

Time:05-28

I am trying to extract some part of a string and put those in array with Ruby.
I have a string like :

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

I want a regex that works with match to extract these parts (pack_1, pack_2, pack_3, pack_4) and then I will put them into array. The end result will be something like:

[pack_1, pack_2, pack_3, pack_4]

Snippet Part :

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

CodePudding user response:

I think this is what you are looking for

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

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

After calling this method variable should be like this

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

Just trim the beginning with slice(7..-1) if you want to get rid of test

"['Alice', 'John', 'Mike', 'test']"
  • Related