本文介绍了如何用 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 中的计算表达式替换?
发布评论