Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a regular expression to replace matches preserving case?

Tags:

regex

How can I use a single regular expression to replace all words town with village preserving the case of the first letter of each match?

Example input:

Towns are small cities. I live in a town.

Desired output:

Villages are small cities. I live in a village.
like image 371
cwd Avatar asked Nov 04 '11 17:11

cwd


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.

Which function is used to match a regular expression?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string.


1 Answers

$_ = "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.
like image 115
tchrist Avatar answered Nov 12 '22 03:11

tchrist