Perl 正则表达式替换计数 [英] Perl regex replace count

查看:69
本文介绍了Perl 正则表达式替换计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定要替换的最大匹配数.例如,如果匹配Hello World"中的 'l',是否可以替换前 2 个 'l' 字符,而不是不循环替换第三个字符?

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?

推荐答案

$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;

这是一个循环,因为当你这样做时 s///g 以一种循环的方式工作.但不是传统的循环.

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

这篇关于Perl 正则表达式替换计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆