简体   繁体   中英

Regular Expression Perl

I am learning regular expression in perl, and i would like to have a function similar as bellow:

sub RegEx() 
{
  my $T = "0,1,";
  my $T2 = "-0:0-0:1-0:2-0:3-0:4-1:0-1:1-1:2-1:3-";

  printf ("T= %s <br>", $T);
  printf ("T2 %s <br>", $T2);

  my @values = split(',', $T);
  foreach my $val (@values) {
         printf ("We are at item %s in T <br>", $val);
         my $temp = $val .":" . "\(\\d\)\+";
         printf ("Rexeg %s <br>",$temp);
         @result = split(/$temp/, $T2);
         foreach my $val2 (@result) {
                printf ("T2- %s <br>", $val2);
         }
   }
}

and have the value of $T2 parsed to an array based on an index ($T)

but The following is being displayed

T= 0,1 
T2 -0:0-0:1-0:2-0:3-0:4-1:0-1:1-1:2-1:3- 
We are at item 0 in T 
Rexeg 0:(\d)+ 
T2- - 
T2- 0 
T2- - 
T2- 1 
T2- - 
T2- 2 
T2- - 
T2- 3 
T2- - 
T2- 4 
T2- -1:0-1:1-1:2-1:3- 
We are at item 1 in T 
Rexeg 1:(\d)+ 
T2- -0:0-0:1-0:2-0:3-0:4- 
T2- 0 
T2- - 
T2- 1 
T2- - 
T2- 2 
T2- - 
T2- 3 
T2- - 

Kindly let me know why i am still seeing

  1. T2- -0:0-0:1-0:2-0:3-0:4- when the regular expression is 1:(\\d)+

  2. "-"

as the output of @results?

split makes no sense. You don't want to split a string. You want:

my @result = $T2 =~ /$temp/g;

You really should include the " - " in your pattern. (Consider what happens when the numbers get to 10.)

my @result = $T2 =~ /-\Q$val\E:(\d+)/g;

( \\Q..\\E is technically no needed if $val is always going to be digits, but it's a good habit.)

That said, I'd probably just parse $T2 once.

my $T2 = "-0:0-0:1-0:2-0:3-0:4-1:0-1:1-1:2-1:3-";
my %T2; push @{ $T2{$1} }, $2 while $T2 =~ /-(\d+):(\d+)/g;
...
my @result = @{ $T2{$val} };
  1. You split on 1:(\\d)+ . What is on the left of the first matching element ? The string you wrote.

  2. You split on 1:(\\d)+ . What is between two matches of this regex ? Dashes.

You split on 1:(\\d)+ . This means, you cut you string into parts, and use the result of the regex as a separator . Globbing using () the integer makes it appear in the global result as a regex match.

Now, you can explain us what you want to achieve, and then we may be able to help you correct yourself one this one.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM