使用perl在句子中匹配句号

时间:2011-12-08 16:01:49

标签: regex perl

如何在句子中匹配句号(句点),但我不想匹配包含数字的浮动数字或单词?

例如。

$sen = "I'm going to match full.stop in sentence 3.142";
if ($sen =~ (s/\.//)) {
    print $1;
}

输出:

fullstop

在这个例子中,我只想匹配单词或字母数字单词而不是数字。

4 个答案:

答案 0 :(得分:3)

使用环顾四周:

$sen =~ s/(?<!\d)\.(?!\d)//g;

这将匹配一个前面没有数字但后面没有数字的点。

根据OP的评论更新,这将删除大写字母后面的点:

#!/usr/bin/perl
use Modern::Perl;
use utf8;

while(<DATA>) {
    chomp;
    s/\.(?=(?:\s*[A-Z])|$)//g;
    # Or, if you want to be unicode compatible
    s/\pP(?=(?:\s*\p{Lu})|$)//g;
    say;
}

__DATA__
I'm going to match full.stop in sentence 3.142
I'm going to match full.Stop in sentence 3.142
I'm going to match full. Stop in sentence 3.142
I'm going to match full.stop in sentence 3.142. End of string.

<强>输出:

I'm going to match full.stop in sentence 3.142
I'm going to match fullStop in sentence 3.142
I'm going to match full Stop in sentence 3.142
I'm going to match full.stop in sentence 3.142 End of string

答案 1 :(得分:0)

您可以使用/(\.(\D|$))|\D\./\D表示非数字字符,$表示行的结尾

答案 2 :(得分:0)

如果要删除第一个句点(“full.stop”中间的句号),但保留第二个句点(3.142中的那个句点),并保留其中的数字,例如“1”。或“p.1223”您可以执行以下操作:

$sen =~ s/(\D)\.(\D)/$1$2/g;
print $sen;

答案 3 :(得分:0)

让reg-exes尽可能简单,这很好,因为它们已经难以阅读了。

要匹配一个或多个非数字和空白,然后匹配'.',然后再匹配一个或多个非数字和非空白:

$sen = "I'm going to match full.stop in sentence 3.142";
print "$1\n" if $sen =~ /([^\d\s]+\.[^\d\s]+)/';

给出:

full.stop

相关问题