如何使用正则表达式替换匹配保留大小写?

时间:2011-11-04 17:45:43

标签: regex

如何使用单个正则表达式将所有单词town替换为village,并保留每个匹配的第一个字母的大小写?

示例输入:

Towns are small cities. I live in a town.

期望的输出:

Villages are small cities. I live in a village.

1 个答案:

答案 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.