I want to split this message into groups:
[Rule] 'Server - update repository' [Source] 10.10.10.10 [User] _Server [Content] HTTP GET http://example.com
Expected result:
Group1: [Rule] 'Server - update repository'
Group2: [Source] 10.10.10.10
Group3: [User] _Server
Group4: [Content] HTTP GET http://example.com
It does not have to be 4 groups, sometimes it can be less / more. Pattern I tried to built:
(\(^\[\w \].*\)){0,}
CodePudding user response:
I would do it like this:
string = "[Rule] 'Server - update repository' [Source] 10.10.10.10 [User] _Server [Content] HTTP GET http://example.com"
regexp = /\[?[^\[] /
string.scan(regexp)
#=> ["[Rule] 'Server - update repository' ", "[Source] 10.10.10.10 ", "[User] _Server ", "[Content] HTTP GET http://example.com"]
Or when you prefer a hash to be returned:
regexp = /\[(\w )\]\s ([^\[] )/
string.scan(regexp).to_h
#=> { "Rule" => "'Server - update repository' ", "Source" => "10.10.10.10 ", "User" => "_Server ", "Content" => "HTTP GET http://example.com" }
CodePudding user response:
If there will be no [ in the group text this might work.
str = "[Rule] 'Server - update repository' [Source] 10.10.10.10 [User] _Server [Content] HTTP GET http://example.com"
str.split("[").each_with_index {|c, i| puts "Group #{i}: [#{c}" if i > 0}
Group 1: [Rule] 'Server - update repository'
Group 2: [Source] 10.10.10.10
Group 3: [User] _Server
Group 4: [Content] HTTP GET http://example.com