perl:从内容中提取第一行

时间:2010-11-03 08:25:11

标签: regex perl

要求:我有很多行的内容。我需要提取第一行并在此之后添加新行。

条件:第一行可以. , ? , !结束,后跟大写字母或任何数字的空格。 . , ? , !之后可能已有新行。在这种情况下,我们需要用单行替换那些额外的新行

例如,如果内容是

案例1

My name is abc. I am working in Software..... 

情况2

My name is abc.
I am working in Software...

在这两种情况下,结果都应该像

My name is abc.
I am working in Software...

解决方案:我尝试了什么:

   $$text =~ s/(.+?[\.\?!$])(\n*)(\s[A-Z0-9])/$1\n$3/smi ;

第二种情况正常。但它并没有在第一种情况下添加新行。 请建议

2 个答案:

答案 0 :(得分:3)

为什么要将$放入角色类? 为什么要使用$$文本?

你可以尝试:

#!/usr/bin/perl
use 5.10.1;
use strict;
use warnings;

my @l = (
"My name is abc. I am working in Software..... ",
"My name is abc.
I am working in Software... 
");

for(@l) {
  s/([.?!])(\n*)\s*/$1\n/smi ;
  say;
}

输出:

My name is abc.
I am working in Software..... 
My name is abc.
I am working in Software... 

答案 1 :(得分:1)

#!/usr/bin/perl
use strict; use warnings;

my @strings = (
    "My name is abc.\nI am working in Software...",
    "Is your name xyz?\n \n How do you do?",
    "My car is red!\n Fire engine red!",
    "Mr.\nBrown goes to Washington.",
);

for my $s ( @strings ) {
    $s =~ s/^( [^.?!]+ [.?!]) \s+ /$1 /x;
    print $s, "\n";
}