我有一个包含要提取的信息的字符串。我的问题是字符串长度可以根据产品版本,用户名,密码等进行更改。因此,我不能只说变量[155:185]。我认为这是一个正则表达式解决方案,但我从未与正则表达式一起工作,并且不确定。
我已经尝试过使用变量[155:185],但是除非字符串长度是确定的,否则这将无法工作。
_____这是我从中提取的字符串_____
[('loginTapped()-登录成功。ID:fakeemail@gmail.com-Password123',),('loginTapped()-登录按钮-版本:1.03.29(29)',),(' logFoundBleNames()-找到bleNames:,VR0796a3',),('viewDidLoad()-viewDidLoad',),('waitTimerSerialNumEvent(timer :)-找到XY设备:VR0796a3和序列号:macAddress:0025ca0796a3',),('wifiScanTimerEvent (计时器:)-请求Wifi列表。名称:VR0796a3',),('refrigeratorTapped()-segue_to_enter_pin_sid',),('viewDidLoad()-viewDidLoad',),('applianceTapped()-segue_to_wifi_select_sid',),( 'viewDidLoad()-viewDidLoad',),('prepare(for:sender :)-segue_to_prod_wifi_setup_sid with:IotTest',),('viewDidLoad()-得到了一个有效的mac:0025ca0796a3',),('viewDidLoad()- viewDidLoad',),('onRecordButton-wifi:IotTest',),('addWifiNameToParamOut(wifi :)-将WiFi名称添加到apParamOut:IotTest',),('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler :)-已调用使用:mac:0025ca0796a3 api密钥:757d1040设备引脚:123 4',),('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler :)-\ nDevice Apikey:c8b428e2 \ n',),('setPassphrase(psswd :)-输入带有device.apParamOut.count的setPassphrase:38-psswd len:9',),('onRecordButton-调用Cloud之后调用updateApplianceRecord()-),('updateApplianceRecord()-更新设备记录:名称:Optional(“ XY0796a3”)mac:0025ca0796a3序列号:appl名称:Optional( “冻结器”)modelID:6',),('setupChangeNotification()-设置完成(通知)。立即返回产品选择屏幕。',),('setupChangeNotification()-在通知调用中调用updateApplianceRecord()')
import _sqlite3
# SQL to readable text
#add a time stamp!!
from Functions import create_connection
global Error
Error = False
try:
UserFile = open("UserFriend.txt", "w")
except:
UserFile = open("UserFriend.txt", "w+")
filename = "perfect_viking_connect.db"
perfect = "perfect_viking_connect.db"
#type1 = "Crash"
#type2 = "Connection Issue"
#cause1 = "Possible too far away"
#cause2 = "Poor connection with router with eiter phone or appliance"
def Friendly_Output(line):
# Begin Searching
####################################################################################################
#Login
#######################################################
if Error == False and "Login in success" in line:
UserFile.write("User Information" + line)
if Error == True and "Login in Success" in line:
UserFile.write("There was a Login Error")
# Version
########################################################
if Error == False and "Login Button" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\nUser is on Version: " + line[42:49])
#else:
#UserFile.write("\nAn error has occurred on login possible errors are") # + type1,type2,type3,type4)
# Found Bluetooth
########################################################
if Error == False and "Found bleNames" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\nSystem has found the Bluetooth name: " + line[41:49] +"\n")
#else:
#UserFile.write("\nAn error has occurred while searching for Appliances Bluetooth")
# Request Wifi List
########################################################
if Error == False and "Found VR" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\n______Wifi information______\nVR Appliance: " + line[56:64] + "\n" + "Serial:\n" + "macAddress: " + line[90:102])
#else:
#UserFile.write("\nAn error has occurred receiving appliance information") # + type1,type2,type3,type4)
# Nic Board wifi request
########################################################
if Error == False and "waitTimerSerialNumEvent" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\n\nNIC is requesting wifi list")
#else:
#pass
# Enter Pin Screen
########################################################
if Error == False and "enter_pin_sid" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\nUser is passed to enter pin screen")
#else:
#UserFile.write("\nAn error has occurred transferring to pin screen") # + type1,type2,type3,type4)")
# Wifi selection screen
########################################################
if Error == False and "wifi_select_sid" in line: # and if next line doesn't load then and Error has occured
UserFile.write(("\nUser is selecting wifi connection from list"))
#else:
#UserFile.write(("\nThere was an error")) # + type1, type2, type3
# Wifi Setup Screen
########################################################
if Error == False and "wifi_setup" in line: # and if next line doesn't load then and Error has occured
UserFile.write("\nUser is on wifi credentials page")
#else:
#UserFile.write("\nAn error has occurred while searching for appliances\n") # + type1,type2,type3,type4)
# User has pressed enter
########################################################
if Error == False and " - wifi: " in line: # and if next line doesn't load then and Error has occured
UserFile.write("\nUser has entered credentials and pressed enter")
#else:
#UserFile.write("\nAn error has occurred while starting the cloud setup process\n") # + type1,type2,type3,type4)
# Adding pass/fail
########################################################
if Error == False and "addWifiNameTo" in line:
UserFile.write("\nUser has successfully added their connection")
#else:
#UserFile.write("\nThe wifi addition process has failed")
''' # Pinging cloud to add new information
########################################################
if Error == False and "addWifiNameTo" in line:
UserFile.write("\nUser has successfully added their connection")
#else:
#UserFile.write("\nThe wifi addition process has failed")'''
########################################################
#Beginning Cloud talk
##########################################################################
if Error == False and "Called with: mac:" in line:
UserFile.write("\n\n____Cloud Talk has Begun____\nMac address: " + line[107:119] + "\nApikey: " + line[128:136] + "\nDevice Pin: " + line[148:152])
if Error == True and "Called with: mac:" in line:
print("Cloud Talk Failed")
#Device Apikey
########################################################
if Error == False and r"\nDevice Apikey:" in line:
UserFile.write("\nDevice Apikey: " + line[106:114])
if Error == True and r"\nDevice Apikey:" in line:
pass
####################################################################################################
def nextrowfinder(Current_Row):
if "Login in success. id:" in Current_Row:
KnowNextRow = "loginTapped() - Login Button - version:"
return KnowNextRow
elif "loginTapped() - Login Button - version:" in Current_Row:
KnowNextRow = "logFoundBleNames() - Found bleNames:"
return KnowNextRow
elif "logFoundBleNames() - Found bleNames:" in Current_Row:
KnowNextRow = "viewDidLoad() - viewDidLoad"
return KnowNextRow
# elif "viewDidLoad() - viewDidLoad" in Current_Row:
# KnowNextRow = "waitTimerSerialNumEvent(timer:) - Found VR Appliance:"
# return KnowNextRow
elif "waitTimerSerialNumEvent(timer:) - Found VR Appliance:" in Current_Row:
KnowNextRow = "wifiScanTimerEvent(timer:) - Wifi list requested. Name:"
return KnowNextRow
elif "wifiScanTimerEvent(timer:) - Wifi list requested. Name:" in Current_Row:
KnowNextRow = "refrigeratorTapped() - segue_to_enter_pin_sid"
return KnowNextRow
elif "refrigeratorTapped() - segue_to_enter_pin_sid" in Current_Row:
KnowNextRow = "viewDidLoad() - viewDidLoad"
return KnowNextRow
#elif "viewDidLoad() - viewDidLoad" in Current_Row:
# KnowNextRow = "applianceTapped() - segue_to_wifi_select_sid"
# return KnowNextRow
elif "applianceTapped() - segue_to_wifi_select_sid" in Current_Row:
KnowNextRow = "viewDidLoad() - viewDidLoad"
return KnowNextRow
#elif "viewDidLoad() - viewDidLoad" in Current_Row:
# KnowNextRow = "prepare(for:sender:) - segue_to_prod_wifi_setup_sid with:"
# return KnowNextRow
elif "prepare(for:sender:) - segue_to_prod_wifi_setup_sid with:" in Current_Row:
KnowNextRow = "viewDidLoad() - Got a valid mac:"
return KnowNextRow
elif "viewDidLoad() - Got a valid mac:" in Current_Row:
KnowNextRow = "viewDidLoad() - viewDidLoad"
return KnowNextRow
#elif "viewDidLoad() - viewDidLoad" in Current_Row:
# KnowNextRow = "onRecordButton - wifi:"
# return KnowNextRow
elif "onRecordButton - wifi:" in Current_Row:
KnowNextRow = "addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut:"
return KnowNextRow
elif "addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut:" in Current_Row:
KnowNextRow = "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac:"
return KnowNextRow
elif "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac:" in Current_Row:
KnowNextRow = "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey:"
return KnowNextRow
elif "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey:" in Current_Row:
KnowNextRow = "setPassphrase(psswd:) - Enter setPassphrase with appliance.apParamOut.count:"
return KnowNextRow
elif "setPassphrase(psswd:) - Enter setPassphrase with appliance.apParamOut.count:" in Current_Row:
KnowNextRow = "onRecordButton - Calling updateApplianceRecord() after Cloud call"
return KnowNextRow
elif "onRecordButton - Calling updateApplianceRecord() after Cloud call" in Current_Row:
KnowNextRow = "updateApplianceRecord() - updating appliance record: name: Optional"
return KnowNextRow
elif "updateApplianceRecord() - updating appliance record: name: Optional" in Current_Row:
KnowNextRow = "setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now."
return KnowNextRow
elif "setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now." in Current_Row:
KnowNextRow = "setupChangeNotification() - Calling updateApplianceRecord() in Notification call"
return KnowNextRow
elif "setupChangeNotification() - Calling updateApplianceRecord() in Notification call" in Current_Row:
KnowNextRow = "End of Setup Log\n\n\n"
return KnowNextRow
elif "viewDidLoad() - viewDidLoad" in Current_Row:
KnowNextRow = "View Load"
return KnowNextRow
else:
KnowNextRow = "Error"
return KnowNextRow
####################################################################################################
def main():
list = create_connection(filename) # create_connection(database)
global Error
#counter = 0
cur = list.cursor()
cur.execute("SELECT error_text from error_log ")
rows = cur.fetchall()
perlist = create_connection(perfect)
percur = perlist.cursor()
percur.execute("SELECT error_text from error_log Where id >= 2")
perrows = percur.fetchall()
#for row in rows:
# counter = counter + 1
#for count in range(counter):
rows_list = []
perrows_list = []
for row in rows:
KnowNextRow = nextrowfinder(str(row))
rows_list.append(KnowNextRow)
for perrow in perrows:
PerfectNextRow = perrow
xx = (str(PerfectNextRow))
perrows_list.append(xx)
rows_len = len(rows_list) # Get length of lists to ensure they are the same
perlen = len(perrows_list)
#print(rows_list)
#print(perrows_list)
for idx, Know_Next in enumerate(rows_list):
if idx < (perlen - 1): # Check that perrows item exists
if Know_Next in perrows_list[idx]:
#print("Match on line " + str(idx))
pass
else:
print("View Did Load Screen")
main()
我想提取模型编号,请尝试使用变量[start:end],但只有在用户放置了确切的字符串长度的情况下,我才能得到它。我想对关键字进行某种搜索并获取其后的文本。
答案 0 :(得分:1)
我只能在您给定的文本中找到这五个信息,分别是用户名,密码,型号,macaddress和applname。我已经构造了一个命名的组正则表达式,因此您可以轻松地掌握其内容。要使用的正则表达式是
(?s)id: (?P<username>.+?) - (?P<password>.+?)'.*Appliance: (?P<modelnumber>\S+).*macAddress: (?P<macaddress>.+?)'.*appl name: (?P<applname>\S+)
此处(?s)
用于启用.
来匹配换行符,并且您的数据似乎跨多行。其余命名组按数据出现的顺序排列。如果您需要从文本中查找更多信息,可以增强正则表达式以类似的方式捕获更多信息,或者在遇到困难时致电给我寻求帮助。
示例Python代码,
import re
s = '''[('loginTapped() - Login in success. id: fakeemail@gmail.com - Password123',), ('loginTapped() - Login Button - version: 1.03.29 (29)',), ('logFoundBleNames() - Found bleNames: , VR0796a3',), ('viewDidLoad() - viewDidLoad',), ('waitTimerSerialNumEvent(timer:) - Found XY Appliance: VR0796a3 and serial: macAddress: 0025ca0796a3',), ('wifiScanTimerEvent(timer:) - Wifi list requested. Name: VR0796a3',), ('refrigeratorTapped() - segue_to_enter_pin_sid',), ('viewDidLoad() - viewDidLoad',), ('applianceTapped() - segue_to_wifi_select_sid',), ('viewDidLoad() - viewDidLoad',), ('prepare(for:sender:) - segue_to_prod_wifi_setup_sid with: IotTest',), ('viewDidLoad() - Got a valid mac: 0025ca0796a3',), ('viewDidLoad() - viewDidLoad',), ('onRecordButton - wifi: IotTest',), ('addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut: IotTest',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac: 0025ca0796a3 apiKey: 757d1040 devicePin: 1234',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey: c8b428e2\n',), ('setPassphrase(psswd:) - Enter setPassphrase with appliance.apParamOut.count: 38 - psswd len: 9',), ('onRecordButton - Calling updateApplianceRecord() after Cloud call',), ('updateApplianceRecord() - updating appliance record: name: Optional("XY0796a3") mac: 0025ca0796a3 serial: appl name: Optional("Freezer") modelID: 6',), ('setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now.',), ('setupChangeNotification() - Calling updateApplianceRecord() in Notification call',)]'''
m = re.search(r"(?s)id: (?P<username>.+?) - (?P<password>.+?)'.*Appliance: (?P<modelnumber>\S+).*macAddress: (?P<macaddress>.+?)'.*appl name: (?P<applname>\S+)", s)
if (m):
print('username: {}, password: {}, modelnumber: {}, macaddress: {}, applname: {}'.format(m.group('username'),m.group('password'),m.group('modelnumber'),m.group('macaddress'),m.group('applname')))
打印您要求的信息,
username: fakeemail@gmail.com, password: Password123, modelnumber: VR0796a3, macaddress: 0025ca0796a3, applname: Optional("Freezer")
答案 1 :(得分:0)
尝试这样的事情:
import re
m = re.search(r'Found XY Appliance:\s*([^,]*)', dblogstring)
m.group(0)
它与方括号()中的文本匹配,该文本不是逗号。它将可靠地提取复杂字符串的动态变化部分。