如何在 Perl 替换中替换匹配之前的所有文本?
我正在读取输入文件 (IN) 的每一行,如果该行以其中一种模式开头,例如“ab”、“cd”、“ef”、“gh”,则将读取的行打印到输出文件 (OUT) ,“ij”等。打印的行的形式为“pattern:100”或“pattern:100:200”。 我需要将“pattern”替换为“myPattern”,即将当前行打印到FILE,但将第一次出现“:”之前的所有文本替换为“myPattern”。 做这个的最好方式是什么?
目前我有:
while ( <IN> )
{
print FILE if /^ab:|^bc:|^ef:|^gh:/;
}
我不确定 substr 替换是否有帮助,因为“模式”可以是“ab”或“cd”或“ef”或“gh”等。
谢谢! 双
I am reading each line of an input file (IN) and printing the line read to an output file (OUT) if the line begins with one of the patterns, say "ab", "cd","ef","gh","ij" etc. The line printed is of form "pattern: 100" or form "pattern: 100:200". I need to replace "pattern" with "myPattern", i.e. print the current line to FILE but replace all the text before the first occurence of ":" with "myPattern". What is the best way to do this?
Currently I have:
while ( <IN> )
{
print FILE if /^ab:|^bc:|^ef:|^gh:/;
}
I am not sure if substr replacement would help as "pattern" can be either "ab" or"cd" or "ef" or "gh" etc.
Thanks!
Bi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一般来说,这样做:
排序将最长的放在前面,这样如果数据有 ab:: 并且 ab 和 ab: 都被替换,则使用 ab: 代替 ab。
Generically, do this like:
The sort puts the longest ones first, so that if the data has ab:: and both ab and ab: are being substituted, ab: is used instead of ab.
默认情况下,Perl 的替换运算符 (a) 使用第一个匹配项,(b) 仅替换一个匹配项,(c) 如果进行了替换则返回 true,如果没有则返回 false。
所以:
应该为你工作。 请注意,由于短路,只会进行一次替换。
Perl's substitution operator by default (a) uses the first match, (b) only replaces one match and (c) returns true if a replacement was made and false if it wasn't.
So:
Should work for you. Note that because of short-circuiting, only one substitution will be made.
我的 Perl 有点生疏,所以语法可能不准确。
编辑:将其放入您的函数中。
My perl is a little rusty, so syntax might not be exact.
edit: Put it in a function for ya.
这可能就是您想要的:
This might be what you want:
执行上面要求的最短方法是重新使用您的代码,但包括替换。
任何左侧图案都将被替换。 如果左侧不匹配,则不会打印任何内容。
The shortest way to do what you ask above is to re-use your code, but include a substitution.
Any of the left hand side patterns will be replaced. If the left hand side does not match, nothing will be printed.