python – 将字符串位置映射到正则表达式输出中的行号

我正在使用
Python中的“类似grep”的实用程序来搜索Oracle源代码文件.编码标准随着时间的推移而发生了变化,因此尝试查找类似“从表a.foo中删除所有内容”的内容可能会跨越多行,具体取决于该段代码的年龄:

s = """-- multiline DDL statement
DELETE
    a.foo f
WHERE
    f.bar = 'XYZ';

DELETE a.foo f
WHERE f.bar = 'ABC';

DELETE a.foo WHERE bar = 'PDQ';
"""

import re

p = re.compile( r'\bDELETE\b.+?a\.foo', re.MULTILINE | re.DOTALL )

for m in re.finditer( p, s ):
    print s[ m.start() : m.end() ]

这输出:

DELETE
    a.foo
DELETE a.foo
DELETE a.foo

我想要的是:

[2] DELETE
[3]     a.foo
[7] DELETE a.foo
[10] DELETE a.foo

是否有快速/简单/内置的方法将字符串索引映射到行号?

最佳答案

lineno = s.count("\n",0,m.start())+1
点赞