user3623221
user3623221

Reputation: 43

Extract information from user input using Regex in Perl

I am trying to access this only parts of user input. Eg. if user inputs a file name like /file/path/test_324_3422.jpg

I want to get only test, 324 and 3422

I have been attempting this, but it does not work:

#!/usr/bin/perl

if(@ARGV != 1){
    print "Error\n";
}
else{
    my $input = $ARGV[0];
    $input =~ /(.)_([\d]+)_([\d]+)/
    print $1, "\n";


}

Upvotes: 1

Views: 58

Answers (1)

hwnd
hwnd

Reputation: 70722

The dot . inside your capture group is only matching a single character.

And you are only printing $1 which is the match of the first capturing group. You need $2 and $3 also if you want to display the matches of those capturing groups as well.

my $input =~ /([a-zA-Z]+)_(\d+)_(\d+)/;
print join(', ', $1, $2, $3), "\n";

If that does not suit your needs, use a negated match for your first capturing group.

my $input =~ /([^\/_]+)_(\d+)_(\d+)/;

Upvotes: 1

Related Questions