[英]Related to regular expressions in Perl
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 . 我想在Perl中使用regex完成此操作。 I want solution that works for the every case of array inside array , like this
我想要适用于array内array的每种情况的解决方案,像这样
A[B[C[D[E[F[10]]]]]]
So, how to create that @str
array ? 那么,如何创建该
@str
数组 ?
You can use a regex pattern to parse this string recursively, and call Perl code to save intermediate values 您可以使用正则表达式模式以递归方式解析此字符串,然后调用Perl代码以保存中间值
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.