简体   繁体   中英

match using regex in perl

HI I am trying to exract some data from a text file in perl. My file looks like this

Name:John
FirstName:Smith
Name:Alice
FirstName:Meyers
....

I want my string to look like John Smith and Alice Meyers

I tried something like this but I'm stuck and I don't know how to continue

 while (<INPUT>) {
        if (/^[Name]/) {
            $match =~ /(:)(.*?)(\n) / 
            $string = $string.$2;
        }
        if (/^[FirstName]/) {
            $match =~ /(:)(.*?)(\n)/ 
            $string = $string.$2;
        }

}

What I try to do is that when I match Name or FirstName to copy to content between : and \\n but I get confused which is $1 and $2

This will put you first and last names in a hash:

use strict;
use warnings;
use Data::Dumper;

open my $in, '<', 'in.txt';
my (%data, $names, $firstname);

while(<$in>){
    chomp;
    ($names) = /Name:(.*)/ if /^Name/; 
    ($firstname) = /FirstName:(.*)/ if /^FirstName/;
    $data{$names} = $firstname;
}

print Dumper \%data;

Through perl one-liner,

$ perl -0777 -pe 's/(?m).*?Name:([^\n]*)\nFirstName:([^\n]*).*/\1 \2/g' file
John Smith
Alice Meyers
while (<INPUT>) {
   /^([A-Za-z])+\:\s*(.*)$/;
   if ($1 eq 'Name') {
      $surname = $2;
   } elsif ($1 eq 'FirstName') {
      $completeName = $2 . " " . $surname;
   } else {
      /* Error */
   }
}

You might want to add some error handling, eg make sure that a Name is always followed by a FirstName and so on.

$1 $2 $3 .. $N , it's the capture result of () inside regex.

If you do something like that , you cant avoid using $1 like variables.

my ($matched1,$matched2) = $text =~ /(.*):(.*)/

my $names = [];
my $name = '';
while(my $row = <>){
  $row =~ /:(.*)/;
  $name = $name.' '.$1;
  push(@$names,$name) if $name =~ / /;
  $name = '' if $name =~ / /;

}

`while(<>){

} `

open (FH,'abc.txt');
my(%hash,@array);
map{$_=~s/.*?://g;chomp($_);push(@array,$_)} <FH>;
%hash=@array;
print Dumper \%hash;

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