MemoryRefresh!

Perl / Search and replace     Search and replace



Questions Answers 0%

Pages   0 from 15
Questions   0 from 20

Reset


Replacement
In the construct $var =~ s/regex/replacement/ the text matched (if any) is replaced by replacement.

$var = "Jeff Friedl"; $var =~ s/Jeff/Jeffrey/; print $var; #Outputs: Jeffrey Friedl Word boudary
If we did that search/replace again, it would end up with Jeffreyrey Friedl. To avoid that we use word-boundary metacharacter.

$var = "Jeffrey Friedl"; $var =~ s/\bJeff\b/Jeffrey/; print $var; #Outputs: Jeffrey Friedl - not Jeffreyrey Friedl Global replacement
The search and replace is done just once. In order to find and replace all matches we use /g "global replacement" modifier.

$var = "Jeff is Jeff Friedl"; $var =~ s/\bJeff\b/Jeffrey/g; print $var; #Outputs: Jeffrey is Jeffrey Friedl Stock prices example
We want to remove digits from stock proces, so 12.37500000392 is reduce to 12.375, yet 37.500 is reduced to 37.50 Metacharacter \d matches a digit, while [1-9]? removes a third posible zero (if any).

$price = "12.37500000392"; $price =~ s/(\d+.\d\d[1-9]?)\d*/$1/; print $price ."n"; #Outputs: 12.375 $price = "37.500"; $price =~ s/(\d+.\d\d[1-9]?)\d*/$1/; print $price ."n"; #Outputs: 37.50

Related Pages

Non-capturing
Shorthands
Search and replace
Lookaround
Text to html


0% 100%
 
 
0 pages 15 pages
1) What Perl's construct for search and replace is correct?





2) What's the Perl construct for search and replace all?







Replacement
In the construct $var =~ s/regex/replacement/ the text matched (if any) is replaced by replacement.

$var = "Jeff Friedl"; $var =~ s/Jeff/Jeffrey/; print $var; #Outputs: Jeffrey Friedl Word boudary
If we did that search/replace again, it would end up with Jeffreyrey Friedl. To avoid that we use word-boundary metacharacter.

$var = "Jeffrey Friedl"; $var =~ s/\bJeff\b/Jeffrey/; print $var; #Outputs: Jeffrey Friedl - not Jeffreyrey Friedl Global replacement
The search and replace is done just once. In order to find and replace all matches we use /g "global replacement" modifier.

$var = "Jeff is Jeff Friedl"; $var =~ s/\bJeff\b/Jeffrey/g; print $var; #Outputs: Jeffrey is Jeffrey Friedl Stock prices example
We want to remove digits from stock proces, so 12.37500000392 is reduce to 12.375, yet 37.500 is reduced to 37.50 Metacharacter \d matches a digit, while [1-9]? removes a third posible zero (if any).

$price = "12.37500000392"; $price =~ s/(\d+.\d\d[1-9]?)\d*/$1/; print $price ."n"; #Outputs: 12.375 $price = "37.500"; $price =~ s/(\d+.\d\d[1-9]?)\d*/$1/; print $price ."n"; #Outputs: 37.50

References









Programming

Php
   
Regex
   
MySQL
   
Css
   
jQuery
   
Git
   


References