[英]Python 3 Using Regex
我需要查看一个字符串,然后使用正则表达式来将数据存储在变量中
这是一个字符串的示例:我必须存储以下数据:
"www","7/27/2016","3:00pm",21.00,N/A,N/A,"12.90 - 21.75",N/A,+0.00,0,N/A
到目前为止,我可以存储第一个符号的日期和时间以及第一个数字,但是我不知道如何遍历字符串的其余部分并存储数字
symb = re.match(r'"(.*?)"', line) #line is the line of string
if symb is not None:
print(symb.group(1))
print()
else:
print("No Match")
print()
date = re.match(r'".+?(\d+/\d+/\d+)"', line)
if date is not None:
print(date.group(1))
print()
else:
return print("No Match")
print()
time = re.match(r'".+?(\d+:\d+[a-z]{2})"', line)
if time is not None:
print(time.group(1))
print()
else:
print("No Match")
print()
#lastPrice = The first number after the time
lastPrice = re.match(r'.+?(\d+\.\d{2}?),', line)
if lastPrice is not None:
print(lastPrice.group(1))
print()
else:
print("No Match")
print()
import re
text = '"www","7/27/2016","3:00pm",21.00,N/A,N/A,"12.90 - 21.75",N/A,+0.00,0,N/A'
regex = r'.*?,"(\d+/\d+/\d{4})","(\d+:\d{2}\w{2})",(\d+\.\d+),N/A,N/A,"(\d+\.\d+) - (\d+\.\d+)",N/A,(\+\d+\.\d+),0,N/A'
listofmatches = re.findall(regex, text)
假设您有多个数据。 否则,仅对第一个数据使用listofmatches[0]
for lines in listofmatches:
date, time, price, a, b, c = lines
# do something with variables
或将re.findall
替换为re.search
listofmatches = re.search(regex, text)
date, time, price, a, b, c = listofmatches.groups()
print(date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.