代码之家  ›  专栏  ›  技术社区  ›  Amine Harbaoui

REGEX切割字符串[关闭]

  •  -2
  • Amine Harbaoui  · 技术社区  · 6 年前

    我刚接触过python,对正则表达式还不够好,

    我有以下文字:

    4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5
    

    我想用这样的regex剪切这个字符串:

    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)
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Joran Beasley    6 年前
    s="0201041aff4c000215023f3d601143013582ba2e1e1603bcb9ffff02cbc5"
    print(re.findall("^(.{10})(.{8})(.{32})(.{4})(.{4})(.{2})",s))
    

        2
  •  3
  •   FHTMitchell    6 年前

    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
    
        3
  •  -2
  •   Newbie    6 年前