写一个python函数把一个文本文件中所有符合正则表达式的行和行号返回
时间: 2024-05-10 15:16:41 浏览: 12
可以使用Python中的re模块来实现正则表达式的匹配,同时使用内置函数enumerate来获取行号。下面是一个示例代码:
``` python
import re
def search_regex_in_file(file_path, regex_pattern):
matched_lines = []
with open(file_path, 'r') as file:
for line_num, line in enumerate(file, start=1):
if re.match(regex_pattern, line):
matched_lines.append((line_num, line.rstrip('\n')))
return matched_lines
```
这个函数接受两个参数:文件路径和正则表达式模式。它将打开文件并遍历所有行,使用re.match()函数来检查每一行是否匹配给定的模式。如果匹配,则将该行及其行号添加到匹配行列表中。最后,返回匹配行列表。
你可以使用类似下面的代码来调用这个函数:
``` python
matched_lines = search_regex_in_file('test.txt', r'\d+\.')
for line_num, line in matched_lines:
print(f"Line {line_num}: {line}")
```
这个代码将使用正则表达式模式`\d+\.`来搜索test.txt文件中以数字和句点结尾的行,并打印出它们的行号和内容。