匹配并替换字符串,除非前面有另一个特定的字符串

时间:2013-11-12 19:47:55

标签: regex perl

我正在使用Perl并且需要有一个正则表达式,如果它包含特定人的姓名,将匹配字符串,例如“Carol Bean”,除非该人有一个标题(Mr。Mrs. Miss Miss) ,并且没有使用消极的外观。

例如:

Carol Bean is nice只有Carol Bean匹配,但Miss Carol Bean is nice没有匹配。

最终目标是将匹配替换为the student, Carol Bean,如下:

Carol Bean is nice.将变为:the student Carol Bean is nice.,但是 Miss Carol Bean is nice.将保持不变,Miss Carol Bean and Carol Bean.将成为Miss Carol Bean and the student, Carol Bean.

如何在不使用负面背后创建这样的正则表达式?

1 个答案:

答案 0 :(得分:1)

也许以下内容会有所帮助(虽然它不会插入逗号):

use strict;
use warnings;

my %hash = map { $_ => 1 } qw/Mr. Mrs. Ms. Miss/;

while (<DATA>) {
    s/(\S*)\s*\K(Carol Bean)/$hash{$1} ? $2 : ($1 ? 't' : 'T') . "he student $2"/ge;
    print;
}

__DATA__
Carol Bean is nice.
Miss Carol Bean is nice.
Miss Carol Bean and Carol Bean.
Carol Bean is not Mrs. Carol Bean.

输出:

The student Carol Bean is nice.
Miss Carol Bean is nice.
Miss Carol Bean and the student Carol Bean.
The student Carol Bean is not Mrs. Carol Bean.