How to extract the substring between two markers? How to extract the substring between two markers? python python

How to extract the substring between two markers?


Using regular expressions - documentation for further reference

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

or:

import retext = '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


>>> s = 'gfgfdAAA1234ZZZuijjk'>>> start = s.find('AAA') + 3>>> end = s.find('ZZZ', start)>>> s[start:end]'1234'

Then you can use regexps with the re module as well, if you want, but that's not necessary in your case.


regular expression

import rere.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?


matomo