如何使用单个正则表达式将所有单词town
替换为village
,并保留每个匹配的第一个字母的大小写?
示例输入:
Towns are small cities. I live in a town.
期望的输出:
Villages are small cities. I live in a village.
答案 0 :(得分:3)
$_ = "Towns are small cities. I live in a town.\n";
s{ \b (?: (T)|(t) ) own }
{ $1 ? "Village" : "village" }xge;
print;
# prints: Villages are small cities. I live in a village.