regex – Perl: Find a line in a txt by matching typed words?

Question:

Good afternoon,

I have a notepad with several lines typed such as:

★ Bayonet
★ Bayonet | Autotronic (Battle-Scarred)
★ Bayonet | Blue Steel (Minimal Wear)
★ Bayonet | Case Hardened (Battle-Scarred)
★ Bayonet | Case Hardened (Factory New)
★ Bayonet | Case Hardened (Field-Tested)

In my code one of the lines will wait for keyboard input asking which name you want to find

use strict;
open(FILEHANDLE,'<','filtradas.txt') or die "Arquivo não pode ser aberto\n";
my @linhas = <FILEHANDLE>;
close(FILEHANDLE);
print "Informe o nome do item que deseja encontrar: ";
my $nome = <STDIN>; chomp($nome);
foreach my $linhas(@linhas) {
chomp($linhas);
if($linhas =~ m/$nome/gi) {
    print $linhas."\n";
}
}

The question is: Is there any way to create a regex that if for example I type in the keyboard input "Bayonet Case" it prints me all the results of the notebook that contains the Bayonet + Case on the same line? In case:

★ Bayonet | Case Hardened (Battle-Scarred)
★ Bayonet | Case Hardened (Factory New)
★ Bayonet | Case Hardened (Field-Tested)

Sorry if I couldn't be clear, if you didn't understand I'll try to explain it another way.

Thanks in advance.

Answer:

Problem solved with the following function:

$nome =~ s/\s+/.*/g;

which turns "bayonet case" into ( "bayonet.*case". ).

Thank you Hernan.

Scroll to Top