【问题标题】:Regex - Split message into groups正则表达式 - 将消息分成组
【发布时间】:2023-01-10 10:07:51
【问题描述】:

我想将此消息分成几组:

[Rule] 'Server - update repository' [Source] 10.10.10.10 [User] _Server [Content] HTTP GET http://example.com

预期结果:

Group1: [Rule] 'Server - update repository'
Group2: [Source] 10.10.10.10
Group3: [User] _Server
Group4: [Content] HTTP GET http://example.com

不一定是4组,有时可以少/多。 我尝试构建的模式:

(\(^\[\w+\].*\)){0,}

【问题讨论】:

    标签: regex ruby regex-group


    【解决方案1】:

    我会这样做:

    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"]
    

    或者当您希望返回哈希值时:

    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" }
    

    【讨论】:

    • 太感谢了!
    • 还有一个问题——是否有可能进一步拆分?因此,例如 Rule 是键,'Server - update repository' 是值
    • @h0llym0lly 我更新了我的答案以解决您的评论。
    • 再次感谢大家! :)
    【解决方案2】:

    如果没有[在小组文本中,这可能有效。

    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
    

    【讨论】:

    • 太感谢了!
    【解决方案3】:

    您也可以使用String#split

    str = "[Rule] 'Server - update repository' [Source] 10.10.10.10 [User] _Server [Content] HTTP GET http://example.com"
    
    str.split(/ +(?=[)/)
      #=> ["[Rule] 'Server - update repository'",
      #    "[Source] 10.10.10.10",
      #    "[User] _Server",
      #    "[Content] HTTP GET http://example.com"]
    

    字符串在一个或多个空格后跟一个左方括号分开。 (?=[) 是一个积极的前瞻.


    如果你想用键:Group1:Group2等创建一个散列,你可以这样写

    arr = str.split(/ +(?=[)/)
    
    arr.each_index.with_object({}) do |i,h|
      h.update("Group#{i+1}".to_sym => arr[i])
    end
      #=> {:Group1=>"[Rule] 'Server - update repository'",
      #    :Group2=>"[Source] 10.10.10.10",
      #    :Group3=>"[User] _Server",
      #    :Group4=>"[Content] HTTP GET http://example.com"} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      相关资源
      最近更新 更多