Python 正则表达式来切割字符串
我是python新手,但正则表达式还不够好 我有以下案文:Python 正则表达式来切割字符串,python,regex,python-3.x,Python,Regex,Python 3.x,我是python新手,但正则表达式还不够好 我有以下案文: 4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5 我想用正则表达式剪切这个字符串,如下所示: 4c00 // the first 4 characters 0215 // the 4 second characters 023f3d601143013582ba2e1e1603bcb9 // after the 32 characters ffff // after the 4 cha
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)
这对正则表达式来说不是问题。这是一个解决方案:
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))
产出:
但对我来说,正则表达式似乎不是解决这个问题的好方法。。。如果您只想获取接下来的n个字符,只需使用字符串切片。如果每组中的字符数从未改变,您可以使用以下方法:
({10})({8})({32})({4})({4})({2})这个切割遵循什么规则?我看不出有什么逻辑。另外,到目前为止,您尝试了什么?您是否打算获得完全相同的输出?这些数字显示了什么具体的东西,还是你只是选择了它?这些应该是确定获取输出模式的某种方法。我更新了我的问题regex似乎根本不适用于此问题为什么不使用
切片
?很好地向他展示了一种比regex更适合此问题的方法:)+1@JoranBeasley虽然在某种程度上我确实有点喜欢正则表达式的解决方案:)哈哈,它可能是一个有点“漂亮”,但这不是解决这个问题的正确方法imho@JoranBeasley是的,我确实考虑过<代码> ITER(text)< /C>解决方案,但是我认为我会保持简单(ISH)<代码> []。在[10,8,32,4],2]中加入n(iSice(ItRx,0,n))<代码>:谢谢,好的解决方案
0201041aff
4c000215
023f3d601143013582ba2e1e1603bcb9
ffff
02cb
c5
s="0201041aff4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5"
print(re.findall("^(.{10})(.{8})(.{32})(.{4})(.{4})(.{2})",s))