ruby - How to regex two sets of data -
ruby - How to regex two sets of data -
i have text contains description of info , ends 2 sets of data:
long text - tags:(array of tags) - url
i need parse text , construction data.
my thought have like:
a="long text. tags:[ex1,ex2,ex3]"
and utilize a = a.partition("tags:")
(partition
splits text on arg) long text on a[0]
, tags on a[2]
, split individual tags. can problem if "tags:"
in long text
, can create tags:
unique create work.
i'm having problem on how should store url. i'm guessing partitioning string on url work, believe there improve way in regex more accommodating data. how should construction info in way allow me retrieve them stored in text?
update: can tell users construction info in way, needs easy. output, need text, array of strings, , url.
so example, can tell users input this:
"this long text, original description have , store text in database. tags:[tag1,tag 2] url:http://google.com"
or tell them construction yaml format. i'm aiming simplicity here.
if work input above, best way regex get:
"this long text, original description have , store text in database." array of "tag1", "tag 2" "http://google.com"
tl;dr
the best thing in case give users simple (but well-commented) template can edit, , have them paste yaml free-form text field. yaml pretty user-friendly, , meant hand-editable. yaml can parsed hash utilize in application.
sample yaml templatethe next basic illustration of yaml markup description, tags, , url defined hash keys. can see how easy users modify, long pay attending indenting continued lines.
:description: long text, original description have , store text in database. :tags: - tag1 - tag2 - tag3 :url: http://example.com
note array info tags indented readability. however, ruby's yaml parser happy if tags weren't indented in particular case.
you create liberal utilize of comments in text template offer yaml formatting help, or document valid keys or values. example:
# create sure indent descriptions longer 1 line! :description: long text, original description have , store text in database. # valid tag names include tag1..tag9, , word "quux." :tags: - tag1 - tag2 - tag3 # utilize total uri scheme, , not domain name. :url: http://example.com
parse yaml you utilize yaml#load or yaml#load_file parse yaml ruby objects. example:
require 'yaml' data1 = yaml.load string_or_here_document data2 = yaml.load_file '/path/to/yaml/file'
yaml input parsed ruby hash given yaml above, next hash object after parsing input string or file:
{:description=> "this long text, original description have , store text in database.", :tags=>["tag1", "tag2", "tag3"], :url=>"http://example.com"}
you can access values other hash object. example:
data1[:url] #=> "http://example.com" data2[:tags] #=> ["tag1", "tag2", "tag3"]
ruby regex parsing
Comments
Post a Comment