Код: Выделить всё
patt = r"(?:bc)?(.*?)(?:ef)?"
a = re.sub(patt, r"\1", "bcdef") # d - as expected
a = re.sub(patt, r"\1", "abcdefg") # adg - as expected
# I'd like to get `d` only without `a` and `g`
# Trying to remove `a`:
patt = r".*(?:bc)?(.*?)(?:ef)?"
a = re.sub(patt, r"\1", "bcdef") # empty !!!
a = re.sub(patt, r"\1", "abcdef") # empty !!!
# make non-greedy
patt = r".*?(?:bc)?(.*?)(?:ef)?"
a = re.sub(patt, r"\1", "bcdef") # d - as expected
a = re.sub(patt, r"\1", "abcdef") # `ad` instead of `d` - `a` was not captured
# make `a` non-captured
patt = r"(?:.*?)(?:bc)?(.*?)(?:ef)?"
a = re.sub(patt, r"\1", "abcdef") # ad !!! `a` still not captured
Как я могу извлечь только d ( подстрока между необязательными подстроками bc и ef) из abcdefg?
Тот же шаблон должен возвращать hij при применении к hij.
Подробнее здесь: https://stackoverflow.com/questions/793 ... substrings