2

我正在使用 Perl 并且需要一个正则表达式来匹配包含特定人名的字符串,例如“Carol Bean”,除非该人有头衔(Mr. Mrs. Ms. 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.

你如何创建这样一个正则表达式而不使用否定的外观?

4

1 回答 1

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.
于 2013-11-12T20:38:00.183 回答