首页 > 解决方案 > 正则表达式剪切字符串

问题描述

我是 python 新手,我对正则表达式还不够好,

我有这段文字:

4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5

我想像这样使用正则表达式来剪切这个字符串:

4c00 // the first 4 characters
0215 // the 4 second characters
023f3d601143013582ba2e1e1603bcb9 // after the 32 characters
ffff // after the 4 characters
02cb // also the 4 characters
c5 // and finally the last two characters

我像这样剪断绳子,但我不喜欢这种方式:

        companyId = advData[10:14]
        advIndicator = advData[14:18]
        proximityUUID = advData[18:50]
        major = int(advData[50:54], 16)
        minor = int(advData[54:58], 16)
        signalPower = int(advData[-2:], 16)

标签: pythonregexpython-3.x

解决方案


这对正则表达式来说不是问题。这是一个解决方案:

text = '0201041aff4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5'

def split_at(s, index):
    return s[:index], s[index:]

res = []
for index in (10, 8, 32, 4, 4, 2):
    first, text = split_at(text, index)
    res.append(first)

print('\n'.join(res))

输出:

0201041aff
4c000215
023f3d601143013582ba2e1e1603bcb9
ffff
02cb
c5

推荐阅读