[英]How to find a string using regex in Python 3?
How to find a string using regex in Python 3? 如何在Python 3中使用正则表达式查找字符串?
textfile.txt TextFile.txt的
21/02/2018
23/02/2018
yes/2s20/2620 A/RB2
417 A/FOüR COT
Python code Python代码
import re
with open('textfile.txt','r') as f:
input_file = f.readlines()
b_list = []
for i in input_file:
s = re.findall(r'^(?=.*/F)(?:[^/\n]*/){1,}[^/\n]*$|^(?=.*A/RB2$)(?:[^/\n]*/){3,}[^/\n]*$',i)
if len(s) > 0:
print(s)
b_list.append(s)
print(b_list,"***********")
Expected Output: 预期产量:
yes/2s20/2620 A/RB2
417 A/FOüR COT
All cleaned up: 全部清理:
import re
b_list = []
match_string = re.compile(r'^(?=.*/F)(?:[^/\n]*/){1,}[^/\n]*$|^(?=.*A/RB2$)(?:[^/\n]*/){3,}[^/\n]*$')
with open('textfile.txt') as f:
for i in f:
match = match_string.match(i)
if match:
print(match.group(0))
b_list.append(match.group(0)) # Unsure what you need in b_list, this will only add the found string
Original answer: 原始答案:
Try putting the for loop under the with statement and removing the need for readlines 尝试将for循环置于with语句下,并消除对readlines的需求
import re
with open('textfile.txt','r') as f:
b_list = []
for i in f:
s = re.match(r'^(?=.*/F)(?:[^/\n]*/){1,}[^/\n]*$|^(?=.*A/RB2$)(?:[^/\n]*/){3,}[^/\n]*$',i)
if s:
print(s.group(0))
b_list.append(s)
Can also still use findall
just wanted to make it clear was only matching a single item per line. 也可以仍然使用
findall
只是想弄清楚每行只匹配一个项目。 Using your original code: 使用原始代码:
s = re.findall(r'^(?=.*/F)(?:[^/\n]*/){1,}[^/\n]*$|^(?=.*A/RB2$)(?:[^/\n]*/){3,}[^/\n]*$',i)
if len(s) > 0:
print(s[0])
b_list.append(s)
My response is in response to your original question before the edit, but I think is similar enough that you can likely still use it. 我的回复是针对您在编辑之前提出的原始问题,但我认为这非常相似,您可能仍可以使用它。
import re
d = """
"21/02/2018","23/02/2018","yes/2s20/2620 A/RB2","417 A/FOüR COT"
"""
regexpr1=r'\d\d\/\d\d/\d\d\d\d\"\,\"\d\d\/\d\d\/\d\d\d\d\",\"(.*?)\"'
s = re.findall(regexpr1, d)
print("Results for regexpr1 are")
print(s)
regexpr2=r'\"\,\"(.*?)\"'
s = re.findall(regexpr2, d)
for x in s:
regexpr=r'\d\d\/\d\d/\d\d\d\d'
z=re.findall(regexpr, x)
if(z):
s.remove(x)
print("Results for regexpr2 are")
print(s)
Output 产量
Results for regexpr1 are
['yes/2s20/2620 A/RB2']
Results for regexpr2 are
['417 A/FOüR COT']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.