如何在perl中使用正则表达式匹配两个实例并替换第一个实例?
如果返回两个匹配项,我只想替换第一个实例。
示例:
$sen = "The quick brown fox jump over the lazy dog, fox is quick";
我怎样才能只匹配第一个fox并将其替换为wolf,反之亦然。
输出:
The quick brown wolf jump over the lazy dog, fox is quick
或:
The quick brown fox jump over the lazy dog, wolf is quick
谢谢。
I want to replace only the first instance if two matches returned.
example:
$sen = "The quick brown fox jump over the lazy dog, fox is quick";
how can i match only the first fox and replace it with wolf and vice versa.
Output:
The quick brown wolf jump over the lazy dog, fox is quick
or:
The quick brown fox jump over the lazy dog, wolf is quick
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用全局选项
/g
对匹配进行计数,将匹配列表分配给空列表以获取计数(比临时变量更好)。第一次更换是基本的。第二个使用计数器,该计数器在每次匹配时递增,并在适当的时间替换。注意使用单词边框
\b
来防止错误匹配,例如firefox
、foxy lady
等。代码:
输出:
如果您想要更可重用的代码,您可以用它制作一个子例程。
然后你甚至可以使用 sub 来进行这两种替换:
Counting matches by using global option
/g
, assign list of matches to an empty list to get a count (better than a temp variable). First replace is basic. Second uses a counter that increments for each match, and replaces at the proper time.Note use of word border
\b
to prevent false matches, such asfirefox
,foxy lady
, etc.Code:
Output:
If you wish a more reusable code, you can make a subroutine out of it.
You could then even use the sub for both substitutions:
检查是否有(至少)两个并替换第一个:
检查是否有(至少)两个并替换第二个:
To check if there are (at least) two and replace the first:
To check if there are (at least) two and replace the second:
默认情况下,替换运算符的作用正是:匹配并替换第一次出现的情况。
以下语句将为您提供第一条输出行:
By default, the substitution operator does exactly that: match and replace the first occurence.
The following statement will get you your first output line:
您的新问题是您想要计数
并替换第 N 个实例
Your new question is that you want the count
and to replace the Nth instance