- 论坛徽章:
- 7
|
回复 47# felonwan
回复 48# yuanquan08
版主 zhlong8 发表于 6楼:- 先把你这个字符串转换成结构化的数据,再想办法找出所有组合。
- 第一步即使不会用正则表达式的方法也可以先分割字符,再用栈组合起来。
- 第二步就是个递归。
复制代码 code:- #!/usr/bin/perl
- # 先把你这个字符串转换成结构化的数据
- sub From {
- map { s/(\w+)/'$1',/g; s/\(/[/g; s/\)/],/g; eval } shift;
- }
- # 想办法找出所有组合
- sub SOp_eq_inxx__p {
- map join( '_', split /\|/ ),
- glob '{' . join( '}{', map join( '|,', @$_ ) . '|', @_ ) . '}';
- }
- # 就是个递归
- sub Extract {
- my ( $Op, @data ) = @{ +shift }[ 1, 0, 2 ];
- $Op eq 'not' ? map { ref $_ ? Extract($_) : $_ } $data[0] :
- $Op eq 'or' ? map { ref $_ ? Extract($_) : $_ } @data :
- SOp_eq_inxx__p map { ref $_ ? [ Extract($_) ] : [$_] } @data ;
- }
- my $String = <DATA>;
- my @Result = Extract From $String;
- print $_ . $/ for @Result;
- __DATA__
- (A interact ((B or C) or (((D inside E) or F) not inside G)))
复制代码 build-in function: join, split, glob, map, shift, eval, eq, ref
perldoc -f X
# sub SOp_eq_inxx__p == sub sop_eq_inxx__p- sub sop_eq_inxx__p {
- my ( $head, $tail ) = qw[{ }];
- my @param = @_;
- my @body = map { join( '|,', @$_ ) . '|' } @param;
- my $body = join $tail . $head , @body;
- my @all = glob $head . $body . $tail;
- my @ret = map { join '_', split /\|/, $_ } @all;
- return @ret;
- }
复制代码 # sop_eq_inxx__p: usage- my @a = sop_eq_inxx__p [1], [ 2, 3, 4 ];
- say join '|', @a; # 1_2|1_3|1_4
- my @b = sop_eq_inxx__p [ 1, 2 ], [ 3, 4 ];
- say join '|', @b; # 1_3|1_4|2_3|2_4
- my @c = sop_eq_inxx__p [ 1, 2 ], [3];
- say join '|', @c; # 1_3|2_3
复制代码 # sub from == sub From- sub from {
- my $s = shift;
- $s =~ s/(\w+)/'$1',/g;
- $s =~ s/\(/[/g;
- $s =~ s/\)/],/g;
- my $arrayref = eval $s;
- return $arrayref;
- }
复制代码 # usage:- sub f1 {
- my $s = shift;
- $s =~ s/(\w+)/'$1',/g;
- $s =~ s/\(/[/g;
- $s =~ s/\)/],/g;
- return $s;
- }
- my $s1 = '(1 2 3)';
- say f1 $s1; # ['1', '2', '3',],
- my $arrayref = from $s1; # $arrayref is an array-reference: [ 1, 2, 3 ]
复制代码 # sub Extract == sub extract- sub extract {
- my $p = shift;
- my @p = @$p;
- my ( $Op, @data ) = @p[ 1, 0, 2 ]; # $p[1] : or, not, inX
- if ( $Op eq 'not' ) {
- my $data = shift @data;
- if ( ref $data ) {
- return extract($data);
- }
- else { return $data }
- }
- elsif ( $Op eq 'or' ) {
- my @return;
- for (@data) {
- if ( ref $_ ) {
- push @return, extract($_);
- }
- else { push @return, $_ }
- }
- return @return;
- }
- else {
- my @return = @data;
- for (@return) {
- if ( ref $_ ) {
- $_ = [ extract($_) ];
- }
- else { $_ = [$_] }
- }
- @return = sop_eq_inxx__p( @return );
- return @return;
- }
- }
复制代码- my $string = <DATA>;
- my @result = extract from $string;
- print $_ . $/ for @result;
- __DATA__
- (A interact ((B or C) or (((D inside E) or F) not inside G)))
复制代码 |
|