具有同一ch的多个实例的子字符串

2024-04-25 03:55:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我用的是Magtek USB读卡器,可以读取卡的信息

从现在起,我可以刷卡,我得到一长串的信息,进入一个Tkinter输入文本框,看起来像这样

%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

这不会产生任何问题,但是如果我想得到下两个变量firstname和lastname

我需要再利用self.variable.find(“^”)因为在格式中,它是在最后一个初始之后使用的

到目前为止,当我尝试这样做时,它还不能重用“^”

关于如何将字符串拆分为单个变量的任何读者:

卡号

名字

有效期


Tags: self信息dataget格式findcardinitial
2条回答

如果你觉得正则表达式很难,你可以把问题分成几个小部分,一次解决一个问题:

data = '%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?'

pieces = data.split('^')    # Divide in pieces, one of which contains name

for piece in pieces:
    if '/' in piece:
        last, the_rest = piece.split('/')
        first, initial = the_rest.split()
        print('Name:', first, initial, last)
    elif piece.startswith('%B'):
        print('Card no:', piece[2:])

正则表达式将为此工作。我没有捕捉到所有的东西,因为你没有详细说明什么是什么,但这里有一个捕捉名字的例子:

import re
data = "%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?"

matches = re.search(r"\^(?P<name>.+)\^", data)

print(matches.group('name'))
# LAST/FIRST INITIAL

如果您不熟悉regex,这里有一种测试模式匹配的方法:https://regex101.com/r/lAARCP/1和一个简介教程:https://regexone.com/

但基本上,我在搜索(两个胡萝卜之间有一个或多个带“+”的东西,^)。你知道吗

实际上,既然你提到了第一个和最后一个分开,你就应该用这个正则表达式:

\^(?P<last>.+)/(?P<first>.+)\^

这个问题也可能会让你感兴趣,因为你会发现两次:Finding multiple occurrences of a string within a string in Python

相关问题 更多 >