regex - Create a regular expression to match YAML keys in Ruby -
based on next info in yaml file, possible create regular look in ruby matches respective grouping , item keys list
source data
groups: groupa: - item 1 - item 3 grouping b: - itema - item 3 c: - 1 - item 3
test string:
groupa item 1 grouping b itema c item 1 c 1 groupa 1
expected match groups
match 1: 1. groupa 2. item 1 match 2: 1. grouping b 2. itema match 3: 1. c 2. 1
thanks help!
ian
================================== update: next tin mans comment -
here's farther background...
a class within plugin exists contains number of methods. each method receives string parsed determine action performed. in methods, contents of string used in subsequent actions - when required regular look used extract (or match) relevant parts of string. unfortunately there no command on upstream code alter process.
in case, string in form "group item status". grouping , item names not single words , each grouping not have contain items. e.g.
"group item 1" "c item 1" "groupa 1"
so, what's needed method of parsing input string respective grouping , item right values passed methods farther downwards line. given other comparable methods in class utilize regular expressions, , there yaml file contains definitive list of grouping - item pairs, regular look first line of thought.
however, open improve approaches
many thanks
ian
why want match in yaml file? load ruby using yaml parser, , search it, or modify in memory.
if want save modified file, yaml parser can emit ruby object yaml, save.
require 'yaml' yaml = ' --- groups: groupa: - item 1 - item 3 grouping b: - itema - item 3 c: - 1 - item 3 ' yaml = yaml.load(yaml) # => {"groups"=>{"groupa"=>["item 1", "item 3"], "group b"=>["itema", "item 3"], "c"=>[1, "item 3"]}} yaml['groups']['groupa'].first # => "item 1" yaml['groups']['group b'][1] # => "item 3" yaml['groups']['c'].last # => "item 3"
based on above definitions, manipulating info done this:
yaml = yaml.load(yaml) groups = yaml['groups'] new_group = { 'groupa_first' => groups['groupa'].first, 'groupb_second' => groups['group b'][1], 'groupc_last' => groups['c'].last } yaml['new group'] = new_group puts yaml.to_yaml
which outputs:
--- groups: groupa: - item 1 - item 3 grouping b: - itema - item 3 c: - 1 - item 3 new group: groupa_first: item 1 groupb_second: item 3 groupc_last: item 3
there's reason have yaml parsers different languages; create easy load , utilize data. take advantage of tool, , utilize ruby modify data, and, if needed, write out again. 1 huge yaml file before i'd think of trying modify on disk considering it's easy in memory.
now, question becomes, how search keys of hash using regex?
yaml['groups'].select{ |k,v| k[/^group/] } # => {"groupa"=>["item 1", "item 3"], "group b"=>["itema", "item 3"]}
once have ones want, can modify contents, substitute them in-memory hash, , write out.
ruby regex yaml
No comments:
Post a Comment