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

标签 regex

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

输入示例:

Towns are small cities. I live in a town.

期望的输出:

Villages are small cities. I live in a village.

最佳答案

$_ = "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.

关于regex - 如何使用正则表达式来替换保留大小写的匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8013625/

相关文章:

regex - 谷歌分析正则表达式 - 替代无负面前瞻

regex - 如何在rewritecond中匹配www和非www?

python - 将 URL 转换为 HTML 链接

python - Pandas :从字符串中去除数字和括号

regex - 特定代码块的 Grep

java - Java 中使用 contains 不匹配字符串

java - 将句子中用破折号分隔的三个或多个数字之间的破折号字符替换为空格

regex - 如何使用 perl “apply” 退格字符

html - 未封闭的 HTML 标签的正则表达式

javascript - 使用 jquery 或正则表达式用点分割字符串但点不在单引号中