3

我正在使用 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

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

4

1 回答 1

8
lineno = s.count("\n",0,m.start())+1
于 2009-10-05T21:34:40.643 回答