Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex replace count

Tags:

regex

perl

Is it possible to specify the maximum number of matches to replace. For instance if matching 'l' in "Hello World", would it be possible to replace the first 2 'l' characters, but not the third without looping?

like image 722
user623879 Avatar asked Jun 26 '11 05:06

user623879


1 Answers

$str = "Hello world!";
$str =~ s/l/r/ for (1,2);
print $str;

I don't see what's so bad about looping.

Actually, here's a way:

$str="Hello world!"; 
$str =~ s/l/$i++ >= 2 ? "l": "r"/eg; 
print $str;

It's a loop, of sorts, since s///g works in a loopy way when you do this. But not a traditional loop.

like image 191
TLP Avatar answered Oct 18 '22 10:10

TLP