简体   繁体   English

在Perl中使用正则表达式进行匹配

[英]match using regex in perl

HI I am trying to exract some data from a text file in perl. 嗨,我正在尝试从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 我希望我的弦看起来像John SmithAlice 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 我想做的是,当我匹配Name或FirstName复制到:\\n之间的内容时,却感到困惑,分别是$1$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一线,

$ 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. 您可能需要添加一些错误处理,例如,确保Name始终跟在FirstName之后,依此类推。

$1 $2 $3 .. $N , it's the capture result of () inside regex. $ 1 $ 2 $ 3 .. $ N,它是()在正则表达式中的捕获结果。

If you do something like that , you cant avoid using $1 like variables. 如果执行类似的操作,就无法避免使用$ 1之类的变量。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM