Home > OS >  How to print rexp in same line in Perl
How to print rexp in same line in Perl

Time:09-21

So if I have read a file contains lines and I need to find regular expressions for each line. How can I display it.

For example: there are 2 lines in the file:

Line number one has 123 and 456
line number two has 789

And ask user for the specific regular expression from user input for example:

Enter a reg expression => /\d{3}/

How can I get the output like this:

Line 1 has 2 match(es) with starting location(s) shown:
123 [20]    456 [28]
Line 2 has 1 match(es) with starting location(s) shown:
789 [20]

I have tried:

print "Enter a reg expression => ";
my $rexp = <>; 
chomp $rexp;

if(/($rexp)/){
   print "S1 and location $-[$1] \n";

or:

my $n = ($line =~ /$rexp/); 
if (/$rexp/){
    for ( my $i = 0;$i<$n; $i  ) {
        no strict 'refs';
        print "Match '$i' at position $-[$i] \n";
    }
} else {
    print "No match \n";
}

But doesnt work. So how can I print out 2(or more than 2) values of the rexp match and location in same line. Thank you

CodePudding user response:

You can use a while loop and m//g to get all matches and save them and the positions in an array, and then print out results using it:

#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;

# Hardcoded RE for demonstration purposes
my $re = qr/\d{3}/;

while (<DATA>) {
    my @matches;
    while (/$re/g) {
        push @matches, "$&: [$-[0]]";
    }
    my $count = @matches;
    say "Line $. has $count match(es) with starting location(s) shown:";
    say join("\t", @matches);
}

__DATA__
Line number one has 123 and 456
line number two has 789

outputs

Line 1 has 2 match(es) with starting location(s) shown:
123: [20]   456: [28]
Line 2 has 1 match(es) with starting location(s) shown:
789: [20]

when run.

  • Related