所以我使用 Magtek USB 读卡器来读取卡信息,
现在,我可以刷卡,然后得到一长串信息,这些信息会进入 Tkinter Entry 文本框,如下所示
%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?
所有数据都已随机化,但这就是格式
我有一个 tkinter 按钮(它从输入框中以我上面包含的格式获取文本并运行它)
def printCD(self):
print(self.carddata.get())
self.card_data_get = self.carddata.get()
self.creditnumber =
self.card_data_get[self.card_data_get.find("B")+1:
self.card_data_get.find("^")]
print(self.creditnumber)
print(self.card_data_get.count("^"))
输出:
%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?
8954756016548963
这不会产生任何问题,但如果我想获取接下来的两个变量名字和姓氏
我需要重用 self.variable.find("^") 因为在格式中它在LAST之前和INITIAL之后使用
到目前为止,当我尝试这样做时,它还无法重用“^”
任何关于如何将该文本字符串拆分为单个变量的接受者:
卡号
名字
姓氏
到期日期
最佳答案
正则表达式可以解决这个问题。我没有捕获所有内容,因为您没有详细说明是什么,但这是捕获名称的示例:
import re
data = "%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?"
matches = re.search(r"\^(?P<name>.+)\^", data)
print(matches.group('name'))
# LAST/FIRST INITIAL
如果您不熟悉正则表达式,这里有一种测试模式匹配的方法:https://regex101.com/r/lAARCP/1 和介绍教程:https://regexone.com/
但基本上,我正在寻找(两个胡萝卜之间带有 .+ 的一个或多个内容,^)。
实际上,既然您提到第一个和最后一个是分开的,您就可以使用这个正则表达式:
\^(?P<last>.+)/(?P<first>.+)\^
您可能也会对这个问题感兴趣,因为它涉及两次查找某些内容:Finding multiple occurrences of a string within a string in Python
关于python - 具有同一字符的多个实例的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582856/