使用python中的regex在字符串中查找完全长度匹配

时间:2018-06-04 07:46:32

标签: python regex

我如何匹配以C88开头的字符串,并使用Python中的正则表达式从03D结束以下文字:

0:d=0  hl=4 l= 266 cons: SEQUENCE
4:d=1  hl=4 l= 257 prim: INTEGER           :C88C87D325BFC86211ED38A05F04F90A92F252E9D6E5425D54F1B27F3888F95B123BFBB634864DEDF0A6B8636830B6AB70011C6B4C6D8368BCD6FC72D1C341B97130737F0BA520D4C44982EA4554AE19CD54F21DA48ECF634C38E3586253FFC815633510FA4FA8B7B1E07E4E2EABF48603EDFB2E53DFA6CC1F894F892B742B84A2CEA29837B1047D7CC401365B3091B6C7DED09CD3BFECD8EAF66F198A80B27DB9DB334CAE200410AE984D3CE413D8BA04833AB5CE7B7FA43CC848143F82B542343D537E4C79DB30FDFDB66B01259CACE9C3D430A38574F3A09278DD4263CACB8A12175CE7A082FBA63A565F31CBA2176C710008C1781E50C5270FE18142B03D
265:d=1  hl=2 l=   3 prim: INTEGER           :010001

可以清楚地看到,字符串和关键字“INTEGER”之间也有一些空格。如果需要,我们知道匹配的确切长度,即512个字符。

1 个答案:

答案 0 :(得分:1)

使用re.search

<强>演示:

import re
s = """0:d=0  hl=4 l= 266 cons: SEQUENCE
4:d=1  hl=4 l= 257 prim: INTEGER           :C88C87D325BFC86211ED38A05F04F90A92F252E9D6E5425D54F1B27F3888F95B123BFBB634864DEDF0A6B8636830B6AB70011C6B4C6D8368BCD6FC72D1C341B97130737F0BA520D4C44982EA4554AE19CD54F21DA48ECF634C38E3586253FFC815633510FA4FA8B7B1E07E4E2EABF48603EDFB2E53DFA6CC1F894F892B742B84A2CEA29837B1047D7CC401365B3091B6C7DED09CD3BFECD8EAF66F198A80B27DB9DB334CAE200410AE984D3CE413D8BA04833AB5CE7B7FA43CC848143F82B542343D537E4C79DB30FDFDB66B01259CACE9C3D430A38574F3A09278DD4263CACB8A12175CE7A082FBA63A565F31CBA2176C710008C1781E50C5270FE18142B03D
265:d=1  hl=2 l=   3 prim: INTEGER           :010001"""

m = re.search("(prim\: INTEGER\s+\:(?P<uuid>[A-Z0-9]{512}))", s)
if m:
    print m.group('uuid')

<强>输出:

C88C87D325BFC86211ED38A05F04F90A92F252E9D6E5425D54F1B27F3888F95B123BFBB634864DEDF0A6B8636830B6AB70011C6B4C6D8368BCD6FC72D1C341B97130737F0BA520D4C44982EA4554AE19CD54F21DA48ECF634C38E3586253FFC815633510FA4FA8B7B1E07E4E2EABF48603EDFB2E53DFA6CC1F894F892B742B84A2CEA29837B1047D7CC401365B3091B6C7DED09CD3BFECD8EAF66F198A80B27DB9DB334CAE200410AE984D3CE413D8BA04833AB5CE7B7FA43CC848143F82B542343D537E4C79DB30FDFDB66B01259CACE9C3D430A38574F3A09278DD4263CACB8A12175CE7A082FBA63A565F31CBA2176C710008C1781E50C5270FE18142B03D