How to extract the substring between two markers?

前端 未结 18 2701
慢半拍i
慢半拍i 2020-11-22 06:02

Let\'s say I have a string \'gfgfdAAA1234ZZZuijjk\' and I want to extract just the \'1234\' part.

I only know what will be the few characte

18条回答
  •  生来不讨喜
    2020-11-22 06:06

    Using regular expressions - documentation for further reference

    import re
    
    text = 'gfgfdAAA1234ZZZuijjk'
    
    m = re.search('AAA(.+?)ZZZ', text)
    if m:
        found = m.group(1)
    
    # found: 1234
    

    or:

    import re
    
    text = 'gfgfdAAA1234ZZZuijjk'
    
    try:
        found = re.search('AAA(.+?)ZZZ', text).group(1)
    except AttributeError:
        # AAA, ZZZ not found in the original string
        found = '' # apply your error handling
    
    # found: 1234
    

提交回复
热议问题