在 Perl 中查找大字符串中找到子字符串的行号
在 perl 字符串中搜索子字符串的行号的最佳方法是什么?例如: 在中搜索“escape”
"How to Format
► put returns between paragraphs
► for linebreak add 2 spaces at end
► _italic_ or **bold**
► indent code by 4 spaces
► backtick escapes `like _so_`
► quote by placing > at start of line
► to make links
<http://foo.com>
[foo](http://foo.com)"
应该给出 6 作为行号。
What is the best way to search for the line number for a substring in perl string? For e.x.:
Searching for "escape" in
"How to Format
► put returns between paragraphs
► for linebreak add 2 spaces at end
► _italic_ or **bold**
► indent code by 4 spaces
► backtick escapes `like _so_`
► quote by placing > at start of line
► to make links
<http://foo.com>
[foo](http://foo.com)"
should give 6 as the line number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我将通过迭代搜索字符串中的目标模式和换行符来解决这个问题:
I would approach this problem by iteratively searching the string for both the target pattern and for newline characters:
要在 Perl/CGI 接口中打印文件中的特定行:
To print a specific line from a file in Perl/CGI interface:
想到了另一个解决办法。在最近的 Perls 中,您可以在字符串上打开文件句柄,然后只需使用特殊的
$.
变量来自动跟踪行号:Thought of another solution. In sufficiently recent Perls, you can open a filehandle onto a string, and then just use the special
$.
variable to automatically keep track of the line number:我将这样做:
这可以避免执行任何行计数工作,除非确实找到了字符串。它使用
@-
变量来找出匹配开始,然后使用tr
< /a> 计算换行符。Here's how I would do it:
This avoids doing any work counting lines unless the string is actually found. It uses the
@-
variable to find out where the match started, and then usestr
to count newlines.$.
这个特殊变量将为您提供输入文件行号,有关更多详细信息,请访问 http://perldoc.perl.org/perlvar.html$.
This special variable will give you the input file line number, for more detail go to http://perldoc.perl.org/perlvar.html假设您的输入文本包含在单个标量中:
This is assuming that your input text is contained in a single scalar: