首页 > 解决方案 > 如何使用正则表达式 python3 从文本文件中查找字符串?

问题描述

如何使用正则表达式查找单词?

文件.txt

CLIENT BILL
BILL
FINAL BILL
TOTAL BILL

蟒蛇代码

  import re
  with open('file.txt','r') as f: 
     input_file = f.readlines()

 for i in input_file:
     s = re.findall(r'L/sBILL',i)
     print(s)

预期输出:

 FINAL BILL
 TOTAL BILL

标签: pythonregex

解决方案


用于re.match此,另一种模式:

for i in input_file:
   if re.match('\w+(s|L) BILL', i.rstrip()):
      print(i.rstrip())

输出:

FINAL BILL
TOTAL BILL

推荐阅读