I have a string written in some text file -
A[B[C[10]]]
I need to extract the information of arrays used in this string. Example, I have to store the information in an array,
@str = (A[], B[], C[10])
I want to accomplish this thing using regex in Perl . I want solution that works for the every case of array inside array , like this
A[B[C[D[E[F[10]]]]]]
So, how to create that @str
array ?
You can use a regex pattern to parse this string recursively, and call Perl code to save intermediate values
Like this
use strict;
use warnings 'all';
use v5.14;
my @items;
my $i;
my $re = qr{
([A-Z]\[) (?{ $items[$i++] = $^N })
(?:
(?R)
|
(\d+) (?{ $items[$i-1] .= $^N })
)
\] (?{ $items[--$i] .= ']' })
}x;
my $s = 'A[B[C[D[E[F[10]]]]]]';
use Data::Dump;
(@items, $i) = ();
dd \@items if 'A[B[C[10]]]' =~ /$re/g;
(@items, $i) = ();
dd \@items if 'A[B[C[D[E[F[10]]]]]]' =~ /$re/g;
["A[]", "B[]", "C[10]"]
["A[]", "B[]", "C[]", "D[]", "E[]", "F[10]"]
A regex + split to pull it off in a concise way :
use v5.14;
my $s = 'A[B[C[D[E[F[10]]]]]]';
$s =~ s/(\w)\[(\d+)?\]*/\1\[\2\] /g;
my @str = split(/ /, $s);
map{print "$_\n"}@str;
prints out:
A[]
B[]
C[]
D[]
E[]
F[10]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.