我正在使用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.
如何在不使用负面背后创建这样的正则表达式?
答案 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.