正则表达式替换字符串,但不替换分配给标量的值
如果我的问题听起来有点尴尬,请原谅我。我正在寻找一个正则表达式,它将替换 perl 源文件中的行号,而不影响分配给标量的值。
我认为下面会让我的问题更清楚一些。假设我有一个如下所示的 Perl 源代码:
1. $foo = 2.4;
2. print $foo;
我想要一个正则表达式来替换这些行号 (1. 2. etc..)
而不影响分配给标量的值,所以在这种情况下$foo
。
谢谢
Please do pardon me if my question sounds a bit awkward. I am looking for a regex which will replace line numbers in perl source file without affecting values assigned to scalars.
I think below will make my question a little bit clearer. Say I have a perl source which looks like this:
1. $foo = 2.4;
2. print $foo;
I would like a regular expression to replace those line numbers (1. 2. etc..)
without affecting value assigned to scalars, and so in this case $foo
.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将正则表达式锚定到行的开头:
以删除数字:
anchor your regexp to the start of the line:
to remove the numbers:
在 Perl 正则表达式中,您可以使用插入符号
^
来表示行的开头。$
代表一行的结束。这些被称为锚点。因此,要在行的开头(仅)查找数字
\d
,您可以搜索如果您想删除这些数字,您可以用任何内容“替换”它们,如
您还想包括数字后面的点,所以你可以尝试
;
但在正则表达式中,点代表“任何字符”,因此您需要转义点才能按字面意思解释脱
字符号
^
在字符集中也有双重作用(它否定它们),我只提及这一点是因为它是学习正则表达式时常见的混乱来源。Within a perl regex you can use the caret symbol
^
to represent the start of a line.$
represents the end of a line. These are known as anchors.So to find a number
\d
at the beginning of a line (only) you can search forIf you wanted to remove those numbers you can "replace" them with nothing, as in
You also want to include the dot after the number, so you might try
;
But in regex a dot represents "any character" so you will need to escape the dot to have it interpreted literally
The caret symbol
^
also serves double-duty in character sets (it negates them), I only mention this as it is a common source of confusion when learning regex.