如何用 Perl 中的计算表达式替换?

编程入门 行业动态 更新时间:2024-10-23 01:54:50
本文介绍了如何用 Perl 中的计算表达式替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有一个文件 dummy.txt

There's a file dummy.txt

内容是:

9/0/2010 9/2/2010 10/11/2010

我必须将月份部分 (0,2,11) 更改为 +1,即 (1,3,12)我写的替换正则表达式如下

I have to change the month portion (0,2,11) to +1, ie, (1,3,12) I wrote the substitution regex as follows

$line =~ s/\/(\d+)\//\/\1+1\//;

正在打印

9/0+1/2010 9/2+1/2010 10/11+1/2010

如何使它在数字上添加 - 3 而不是执行字符串连接?2+1??

How to make it add - 3 numerically than perform string concat? 2+1??

推荐答案

三个变化:

  • 您必须使用 e 修饰符允许在更换零件.
  • 全局替换你应该使用 g 修饰符.如果每行有一个日期,则不需要.
  • 您在替换方面使用 $1,而不是反向引用
  • You'll have to use the e modifier to allow an expression in the replacement part.
  • To make the replacement globally you should use the g modifier. This is not needed if you've one date per line.
  • You use $1 on the replacement side, not a backreference

这应该有效:

$line =~ s{/(\d+)/}{'/'.($1+1).'/'}eg;

此外,如果您的正则表达式包含您正在使用的分隔符(在您的情况下为/),最好选择不同的分隔符(上面的{}),这样您不必转义正则表达式中的分隔符,使您的正则表达式变得干净.

Also if your regex contains the delimiter you're using(/ in your case), it's better to choose a different delimiter ({} above), this way you don't have to escape the delimiter in the regex making your regex clean.

更多推荐

如何用 Perl 中的计算表达式替换?

本文发布于:2023-06-05 19:41:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/526449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   如何用   Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!