How to parse YAML with zero values?

I apologize for the specific problem that I am posting here, but hope this helps others who may also encounter this problem. I have a string that is formatted as follows:

[[,action1,,],[action2],[]]

I would like to translate this into a valid YAML so that it can be parsed so that it looks like this:

[['','acton1','',''],['action2'],['']]

I tried a bunch of regular expressions for this, but I'm afraid that I have a complete loss. I am fine with running multiple expressions if necessary. For example (ruby):

puts s.gsub!(/,/,"','")  # => [[','action1','',']','[action2]','[]]
puts s.gsub!(/\[',/, "['',") # => [['','action1','',']','[action2]','[]]

What happens there, but I have a feeling that I am starting to descend from the rat moon with this approach. Is there a better way to do this?

Thanks for the help!

+3
3

(ruby1.9):

s.gsub(/(?<=[\[,])(?=[,\]])/, "''")

ruby1.8, :

s.gsub(/([\[,])(?=[,\]])/, "\\1''")

:

s.gsub(/(?<=[\[,])\b|\b(?=[,\]])/, "'")
s.gsub(/(\w+)/, "'\\1'")

('< =' '(? =').

, , . perlre.

+4

, YAML.


Ruby, Perl.


YAML, , JSON, JSON.

Regexp::Grammars, .

, , .

#! /usr/bin/env perl
use strict;
#use warnings;
use 5.010;
#use YAML;
use JSON;
use Regexp::Grammars;


my $str = '[[,action1,,],[action2],[],[,],[,[],]]';

my $parser = qr{
  <match=Array>

  <token: Text>
    [^,\[\]]*

  <token: Element>
  (?:
    <.Text>
  |
    <MATCH=Array>
  )

  <token: Array>
  \[
     (?:
       (?{ $MATCH = [qw'']; })
     |
       <[MATCH=Element]>   ** (,)
     )
  \]
}x;


if( $str =~ $parser ){
  say to_json $/{match};
}else{
  die $@ if $@;
}

.

[["","action1","",""],["action2"],[],["",""],["",[],""]]

YAML, "use YAML;" to_json() Dump()

---
-
  - ''
  - action1
  - ''
  - ''
-
  - action2
- []
-
  - ''
  - ''
-
  - ''
  - []
  - ''
+3

Try the following:

s.gsub(/([\[,])(?=[,\]])/, "\\1''")
 .gsub(/([\[,])(?=[^'\[])|([^\]'])(?=[,\]])/, "\\+'");

EDIT: I'm not sure about the replacement syntax. This should be group No. 1 in the first gsub, and the participating group with the highest number $+- in the second.

+1
source

Source: https://habr.com/ru/post/1715583/


All Articles