How to extract the substring between two markers?

前端 未结 18 2567
慢半拍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:17

    regular expression

    import re
    
    re.search(r"(?<=AAA).*?(?=ZZZ)", your_text).group(0)
    

    The above as-is will fail with an AttributeError if there are no "AAA" and "ZZZ" in your_text

    string methods

    your_text.partition("AAA")[2].partition("ZZZ")[0]
    

    The above will return an empty string if either "AAA" or "ZZZ" don't exist in your_text.

    PS Python Challenge?

提交回复
热议问题