Aditya KV
Aditya KV

Reputation: 11

Perl regex matching - Using * on both sides of the equation

I'm trying to write a script that accepts a string input, and a file input.

The string input would look like:

input_range*_blah

The file would contain lines like so

*_blah
input*_*ah
blah1
blah2
blah3 

I want the script to produce matches for the first and second lines in this particular example.

I am unable to figure out the syntax for this, would someone please help me out? Thanks in advance!

Upvotes: 0

Views: 274

Answers (2)

Tim Pierce
Tim Pierce

Reputation: 5664

If I understand the problem correctly, your file consists of a list of patterns, and you want to print out each of the patterns that matches your input string. So you would print *_blah and input*_*ah because both of those patterns match input_range*_blah, but not blah1 or the following patterns, because they don't match the input string.

In that case, I don't think you need any special handling of the asterisks. In the target string, an asterisk is just another character -- it's not interpreted any special way. This code should do it:

#! /usr/bin/perl

use warnings;
use strict;

use Text::Glob qw/match_glob/;

my $input_string = $ARGV[0];
shift;

while (defined (my $pattern = <>)) {
    chomp $pattern;
    print $pattern, "\n" if (match_glob($pattern, $input_string));
}

Demo: using a file glob.dat containing your example strings:

$ perl glob.pl 'input_range*_blah' glob.dat
*_blah
input*_*ah

Upvotes: 1

fugu
fugu

Reputation: 6578

You need to escape the * characters in your match. Try using this regex:

use warnings;
use strict; 

open my $input, '<', 'in.txt' or die "$!";

my $match = '(.*\*.*)'; 

while (<$input>){
    chomp;
    print "$_\n" if /$match/;
}

Which will declare a variable as a match for anything before or after a literal * and, reading your input file line by line, print out those lines that match it

Upvotes: 0

Related Questions